2014-09-04 63 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

相關問題