使用基类反射派生类的属性

本文关键字:属性 派生 反射 基类 | 更新日期: 2023-09-27 18:20:37

是否可以使用基类在派生类中的overriden属性上应用某个属性?假设我有一个类Person和一个从Person继承的类PersonForm。此外,PersonForm还有一个属性(比方说MyAttribute),用于它的一个属性,该属性是从基Person类中重写的:

public class Person
{
    public virtual string Name { get; set; }
}
public class PersonForm : Person
{
    [MyAttribute]
    public override string Name { get; set; }
}
public class MyAttribute : Attribute
{  }

现在,我的项目中有一个通用的保存函数,它将在某个时刻接收Person类型的对象。问题是:在使用Person对象时,我可以从派生的PersonForm中看到MyAttribute吗?

在现实世界中,这种情况发生在MVC应用程序中,我们使用PersonForm作为显示表单的类,使用Person类作为Model类。当使用Save()方法时,我得到了Person类。但是属性在PersonForm类中。

使用基类反射派生类的属性

我认为这更容易通过代码进行解释,我还将对Person类进行一些小的更改,以突出显示某些内容。

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
   }
}

希望这能有所帮助。