2014-02-27 5 views
1

의 모든 속성이 예를 들어 아래의 샘플 코드를 가지고거야? 재정의 할 재산

나는 아래의 코드를 시도하십시오 property.DeclaringType를 찾을 수 있습니다 마음에 온

[Test] 
    public void testMultipleAttribs() 
    { 
     var property = typeof(SpecificStudent).GetProperties().FirstOrDefault(x => x.Name == "Name"); 

     var attribList = property.Attributes; //returns none 
     var customAttribs = property.CustomAttributes.ToList(); //returns 1 
     var customAttribs2 = property.GetCustomAttributes(inherit: true);// returns 1 
     int k = 5; 

    } 

하나의 솔루션 및 과정을 반복, 그리고 그것에 대한 속성을 얻을. 그러나, 나는 이것을하는 우아한 방법이 아니며, 더 좋은 방법이 있는지 궁금해하고있었습니다.

+1

이해가되지 않는 한 질문 제목에 사용 된 언어에 대한 정보는 포함하지 마십시오 그것없이. 태그는 이러한 용도로 사용됩니다. –

답변

0

TestMultipleAttributes이라는 속성 하나만 있고 덮어 썼습니다. 속성에 두 개 이상의 속성 (PriorityHelpMessage)이 올바르게 작동합니다.

StudentAttributeSpecificStudentAttribute처럼 "실제"더 많은 속성을 만들 수 있습니다.

0

나는 이것이 비교적 우아하다는 것을 잘 모른다. (비록 적어도 하나의 특별한 경우는 빠져있다.) 상속 체인의 재정의 또는 가상 속성에 대한 모든 사용자 지정 특성을 가장 가까운 순서로 열거해야합니다.

public static IEnumerable<Attribute> AllAttributes(PropertyInfo pi) 
{ 
    if (pi != null) 
    { 
    // enumerate all the attributes on this property 
    foreach (object o in pi.GetCustomAttributes(false)) 
    { 
     yield return (Attribute) o ; 
    } 

    PropertyInfo parentProperty = FindNearestAncestorProperty(pi) ; 
    foreach(Attribute attr in AllAttributesRecursive(parentProperty)) 
    { 
     yield return attr ; 
    } 

    } 

} 

private static PropertyInfo FindNearestAncestorProperty(PropertyInfo property) 
{ 
    if (property == null) throw new ArgumentNullException("property") ; 
    if (property.DeclaringType == null) throw new InvalidOperationException("all properties must belong to a type"); 

    // get the property's nearest "ancestor" property 
    const BindingFlags flags = BindingFlags.DeclaredOnly 
          | BindingFlags.Public | BindingFlags.NonPublic 
          | BindingFlags.Static | BindingFlags.Instance 
          ; 
    Type   t  = property.DeclaringType.BaseType ; 
    PropertyInfo ancestor = null ; 

    while (t != null && ancestor == null) 
    { 
    ancestor = t.GetProperty(property.Name,flags) ; 
    t  = t.BaseType ; 
    } ; 

    return ancestor ; 
}