【问题标题】:Reflect attributes from the derived class using base class使用基类反映派生类的属性
【发布时间】:2014-09-04 16:46:31
【问题描述】:

是否可以使用基类在派生类中的覆盖属性上看到某个属性? 假设我有一个 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 类中。

【问题讨论】:

标签: c# attributes


【解决方案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
   }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多