2014-09-04 2 views
0

Возможно ли увидеть определенный атрибут, применяемый к свойству overriden в производном классе, используя базовый класс? Предположим, у меня есть класс Person и класс PersonForm, который наследуется от Person. Также 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 я могу увидеть MyAttribute из производного PersonForm?

В реальном мире это происходит в приложении 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

ответ

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

Смежные вопросы