emilpytka
emilpytka

Reputation: 773

Access to base class from Property Attribute

I'm trying to create attribute which will generate identity number key for each object in class range. So i need to know which class contain parameter connected with attribute. I create something like this:

class SampleModel
{
    [Identity(typeof(SampleModel))]
    public int Id { get; set; }
}


public class IdentityAttribute : Attribute
{
    private readonly int _step;
    private readonly Type _objectType;

    public IdentityAttribute(Type type)
    {
        _step = 1;
        _objectType = type;
    }

    public object GenerateValue()
    {
        return IdentityGenerator.GetGenerator(_objectType).GetNextNum(_step);
    }
}

But i'm wondering is there any method which will allow me to get Type of base class (in this case SampleMethod) in IdentityAttribute constructor without sending it as parameter?

Upvotes: 1

Views: 114

Answers (1)

Jon
Jon

Reputation: 437376

There is no such method -- an instance of Attribute does not know what it was decorating.

But the code that creates the instance does, so depending on usage you could inject this information externally:

 var identityAttribute = (IdentityAttribute)Attribute.GetCustomAttribute(...);

 // If you can call GetCustomAttribute successfully then you can also easily
 // find which class defines the decorated property
 var baseClass = ... ;

 // And pass this information to GenerateValue
 var value = identityAttribute.GenerateValue(baseClass);

Upvotes: 1

Related Questions