2010-04-09 5 views

답변

8

이 중첩 된 형태의 탐사 사용하여 수행 할 수 있습니다 :

public IEnumerable<PropertyInfo> GetRequiredProperties() 
{ 
    var nestedTypes = typeof(Address).GetNestedTypes(BindingFlags.NonPublic); 

    var nestedType = nestedTypes.First(); // It can be done for all types 

    var requiredProperties = 
     nestedType.GetProperties() 
      .Where(property => 
          property.IsDefined(typeof(RequiredAttribute), false)); 

    return requiredProperties; 
} 

사용 예 : 엘리사의 솔루션 적은 다음 우아하지만

[Test] 
public void Example() 
{ 
    var requiredProperties = GetRequiredProperties(); 
    var propertiesNames = requiredProperties.Select(property => property.Name); 

    Assert.That(propertiesNames, Is.EquivalentTo(new[] { "Address1", "Zip" })); 
} 
+0

니스! 고마워. –

+1

이것이 작동하는 동안 'buddy'(메타 데이터) 클래스의 관계가 속성을 통해 정의 된대로 잘못 가정됩니다. 다시 말해, 이상적인 해결책은'MetadataTypeAttribute'가'GetNestedTypes()'가 아닌 버디 유형을 얻기 위해 루트 유형을 검사하는 것입니다. 이 메소드는 중첩되지 않는 한 그러한 모든 유형의 클래스에 유효하지 않습니다. 또한 중첩 된 다른 클래스의 메타 데이터 클래스에 정의되지 않은 속성에 대해서도'RequiredAttribute'를 반환합니다 (존재하는 경우) – JoeBrockhaus

0

을, 그러나 또한 작동합니다 :)

귀하의 속성 :

(210)

일부 클래스 :

class Class1 
{ 
    [Required] 
    public string Address1 { get; set; } 

    public string Address2 { get; set; } 

    [Required] 
    public string Address3 { get; set; } 
} 

사용법 :

Class1 c = new Class1(); 
RequiredAttribute ra = new RequiredAttribute(); 

Type class1Type = c.GetType(); 
PropertyInfo[] propInfoList = class1Type.GetProperties(); 
foreach (PropertyInfo p in propInfoList) 
{ 
    object[] a = p.GetCustomAttributes(true); 
    foreach (object o in a) 
    { 
     if (o.GetType().Equals(ra.GetType())) 
     { 
      richTextBox1.AppendText(p.Name + " "); 
     } 
    } 
} 
0

여기 내 솔루션입니다 usinjg AssociatedMetadataTypeTypeDescriptionProvider :

var entity = CreateAddress(); 
var type = entity.GetType(); 
var metadata = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault(); 
var properties = new AssociatedMetadataTypeTypeDescriptionProvider(type, metadata.MetadataClassType).GetTypeDescriptor(type).GetProperties(); 
bool hasAttribute = HasMetadataPropertyAttribute(properties, "Name", typeof(RequiredAttribute)); 

private static bool HasMetadataPropertyAttribute(PropertyDescriptorCollection properties, string name, Type attributeType) 
{ 
    var property = properties[name]; 
    if (property == null) 
     return false; 

    var hasAttribute = proeprty.Attributes.Cast<object>().Any(a => a.GetType() == attributeType); 
    return hasAttribute; 
}