2014-09-04 2 views
0

기본 클래스를 사용하여 파생 클래스의 재정의 속성에 적용된 특정 특성을 볼 수 있습니까? Person으로부터 상속받은 Person 클래스와 PersonForm 클래스가 있다고 가정 해 보겠습니다. 내가 내 프로젝트에있는 것은 일반적인 저장 기능 지금기본 클래스를 사용하여 파생 클래스의 특성 반영

public class Person 
{ 
    public virtual string Name { get; set; } 
} 

public class PersonForm : Person 
{ 
    [MyAttribute] 
    public override string Name { get; set; } 
} 

public class MyAttribute : Attribute 
{ } 

: 또한 PersonForm은은 기본, 사람, 클래스에서 재정의 된,이 속성의 하나에 사용되는 속성 (의이 MyAttribute을 가정 해 봅시다)가 그것은 한 순간에 Person 유형의 객체를 받게 될 것입니다. 질문 : Person 개체를 사용하는 동안 파생 된 PersonForm에서 MyAttribute를 볼 수 있습니까?

현실 세계에서 이것은 우리가 PersonForm을 폼을 표시하는 클래스로 사용하고 Person 클래스를 Model 클래스로 사용하는 MVC 애플리케이션에서 발생합니다. Save() 메소드를 사용할 때, 나는 Person 클래스를 얻는다. 그러나 속성은 PersonForm 클래스에 있습니다.

+0

[Attribute.GetCustomAttributes 메서드 (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

관련 문제