2014-09-04 110 views
0

是否有可能使用基类在派生类中的overriden属性上应用某个属性? 比方说,我有一个Person类和一个继承自Person的Person类。另外,为personForm具有一个在它的属性之一使用的属性(比如说MyAttribute),这是从基础,人,类重写:使用基类反映派生类中的属性

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类中。

+0

[Attribute.GetCustomAttributes Method(MemberInfo,Boolean)](http://msdn.microsoft.com/en-us/library/ms130868(v = vs.110).aspx)将第二个参数设置为true。 – Yuriy 2014-09-04 16:48:21

回答

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

希望这会有所帮助。

+0

它完美地工作。谢谢! – John 2014-09-04 18:38:20