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

时间:2014-09-04 16:46:31

标签: c# attributes

是否可以使用基类在派生类中的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类中。

1 个答案:

答案 0 :(得分:1)

通过我认为的代码更容易解​​释,我也会对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
   }
}

希望这有帮助。

相关问题