2012-01-20 4 views
5

그래서 루프를 통해 원하는 클래스의 속성 컬렉션이 있습니다. 각 속성마다 맞춤 속성이있을 수 있으므로 그 속성을 반복하고 싶습니다. 나는 속성을 통해 루프 시도 [잘 작동하는]와 때이 특정 경우 나는 속성이 같은속성에서 사용자 지정 특성

[AttributeUsage(AttributeTargets.All)] 
public class ColumnName : System.Attribute 
{ 
    public readonly string ColumnMapName; 
    public ColumnName(string _ColumnName) 
    { 
     this.ColumnMapName= _ColumnName; 
    } 
} 

으로 정의된다 같은

public class City 
{ 
    [ColumnName("OtroID")] 
    public int CityID { get; set; } 
    [Required(ErrorMessage = "Please Specify a City Name")] 
    public string CityName { get; set; } 
} 

로 내 도시 클래스에 사용자 정의 속성이 그런 다음 속성을 반복하면서 속성에 대한 for 루프를 + 시하 고 아무 것도 리턴하지 않습니다. 내가

?Property.GetCustomAttributes(true)[0] 

을 할 수있는 속성 정의를 가지고있는 속성에 대한 직접 실행 창에 갈 때

foreach (PropertyInfo Property in PropCollection) 
//Loop through the collection of properties 
//This is important as this is how we match columns and Properties 
{ 
    System.Attribute[] attrs = 
     System.Attribute.GetCustomAttributes(typeof(T)); 
    foreach (System.Attribute attr in attrs) 
    { 
     if (attr is ColumnName) 
     { 
      ColumnName a = (ColumnName)attr; 
      var x = string.Format("{1} Maps to {0}", 
       Property.Name, a.ColumnMapName); 
     } 
    } 
} 

내가 일이 맞게 보일 수 없다 ColumnMapName: "OtroID"

돌아갑니다 프로그래밍 방식으로도

+1

할 수 : 규칙에 따라 특성 클래스는'ColumnNameAttribute' 호출해야합니다. – Heinzi

+3

'typeof (T)'에서'T'는 무엇인가요? 직접 창에서 Property.GetCustomAttribute (true) [0]을 호출하지만 대신 foreach 루프 내에서 TypeParameter에 대해 GetCustomattributes를 호출합니다. –

+0

Type 매개 변수 만 허용하는 Attribute.GetCustomAttributes() 오버로드가 표시되지 않습니다.속성을 검색하는 행이 맞는지 확인 하시겠습니까? – JMarsch

답변

2

Repost.asp가, 저자는 T가 대해서 typeof (T)에 무엇을 그냥 관심 밖으로

요청에?

직접 실행 창에서 Property.GetCustomAttribute (true) [0]을 호출하지만 foreach 루프 내부에서 대신 typeparameter에서 GetCustomattributes를 호출하고 있습니다.

이 줄 :

System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(T)); 

해야지이

System.Attribute[] attrs = property.GetCustomAttributes(true); 

안부, 보조 노트로

8

나는 이것을하고 싶다. 나는 믿는다 :

PropertyInfo[] propCollection = type.GetProperties(); 
foreach (PropertyInfo property in propCollection) 
{ 
    foreach (var attribute in property.GetCustomAttributes(true)) 
    { 
     if (attribute is ColumnName) 
     { 
     } 
    } 
} 
1

내부보기에서 typeof (T)가 아닌 Properties를 조사해야합니다.

intellisense를 사용하여 Property 개체를 호출 할 수있는 메서드를 살펴보십시오.

Property.GetCustomAttributes (Boolean)가 중요 할 수 있습니다. 이렇게하면 배열이 반환되고 LINQ를 사용하여 요구 사항에 맞는 모든 특성을 빠르게 반환 할 수 있습니다.

1

나는 x의 값이 "OtroID Maps to CityID" 인이 코드를 얻었습니다. 원래 질문의 댓글에서

var props = typeof(City).GetProperties(); 
foreach (var prop in props) 
{ 
    var attributes = Attribute.GetCustomAttributes(prop); 
    foreach (var attribute in attributes) 
    { 
     if (attribute is ColumnName) 
     { 
      ColumnName a = (ColumnName)attribute; 
      var x = string.Format("{1} Maps to {0}",prop.Name,a.ColumnMapName); 
     } 
    } 
} 
관련 문제