Reputation: 495
Is it possible to see a certain attribute applied on a overriden property in derived class, using the base class? Let's say I have a class Person and a class PersonForm that inherits from Person. Also the PersonForm has an Attribute (Let's say MyAttribute) that is used on one of it's properties, that was overriden from the base, Person, class:
public class Person
{
public virtual string Name { get; set; }
}
public class PersonForm : Person
{
[MyAttribute]
public override string Name { get; set; }
}
public class MyAttribute : Attribute
{ }
Now what I have in my project is a generic save function that will receive at one moment the object of type Person. The question is: While using the Person object, can I see the MyAttribute from the derived PersonForm?
In real world this happens in an MVC application where we use the PersonForm as the class for displaying the form, and the Person class as the Model class. When coming to the Save() method, I get the Person class. But the attributes are in the PersonForm class.
Upvotes: 0
Views: 76
Reputation: 430
This is easier to explain through code I think and I will also make a minor change to the Person class to highlight something.
public class Person
{
[MyOtherAttribute]
public virtual string Name { get; set; }
[MyOtherAttribute]
public virtual int Age { get; set; }
}
private void MyOtherMethod()
{
PersonForm person = new PersonForm();
Save(person);
}
public void Save(Person person)
{
var type = person.GetType(); //type here is PersonForm because that is what was passed by MyOtherMethod.
//GetProperties return all properties of the object hierarchy
foreach (var propertyInfo in personForm.GetType().GetProperties())
{
//This will return all custom attributes of the property whether the property was defined in the parent class or type of the actual person instance.
// So for Name property this will return MyAttribute and for Age property MyOtherAttribute
Attribute.GetCustomAttributes(propertyInfo, false);
//This will return all custom attributes of the property and even the ones defined in the parent class.
// So for Name property this will return MyAttribute and MyOtherAttribute.
Attribute.GetCustomAttributes(propertyInfo, true); //true for inherit param
}
}
Hope this helps.
Upvotes: 1