2010-06-06 5 views
3

속성 내에서 상위 클래스에 액세스 할 수 있습니까?맞춤 속성에서 상위 클래스에 액세스

예를 들어 MVC에서 viewmodel 클래스의 속성에 적용 할 수있는 DropDownListAttribute를 만든 다음 편집기 템플릿에서 드롭 다운 목록을 만듭니다. 나는 Kazi Manzur Rashid here과 유사한 행을 따랐다.

그는 범주의 컬렉션을 뷰 데이터에 추가하고 속성에 제공된 키를 사용하여 검색합니다.

나는

public ExampleDropDownViewModel { 

    public IEnumerable<SelectListItem> Categories {get;set;} 

    [DropDownList("Categories")] 
    public int CategoryID { get;set; } 
} 

속성은 바인딩 할 컬렉션을 포함하는 속성의 이름을 소요, 아래 같은 일을하고 싶습니다. 속성의 상위 클래스에있는 속성에 액세스하는 방법을 알 수 없습니다. 누구든지이 작업을 수행하는 방법을 알고 있습니까?

감사합니다.

답변

1

속성에서 상위 유형에 액세스 할 수 없습니다. 속성은 유형에 적용되는 메타 데이터,하지만 당신은 같은 짓하지 않는 한 당신은, 다시보고 시도 유형을 식별 할 수 없습니다 위의 반사 솔루션

[MyCustomAttribute(typeof(MyClass))] 
public class MyClass { 
    /// 
} 

을, 당신은 실제로 작업을 달성하지 않습니다 특성에서 유형을 가져 오는 경우, 역순으로 수행하면 유형에서 속성을 얻게됩니다. 이 시점에서 이미 유형이 있습니다.

1

리플렉션을 사용하여이를 수행 할 수 있습니다. 기본 클래스에서 다음을 수행하십시오.

Type type = typeof(ExampleDropDownViewModel)); 
// Get properties of your data class 
PropertyInfo[] propertyInfo = type.GetProperties(); 

foreach(PropertyInfo prop in propertyInfo) 
{ 
    // Fetch custom attributes applied to a property   
    object[] attributes = prop.GetCustomAttributes(true); 

    foreach (Attribute attribute in attributes) { 
     // we are only interested in DropDownList Attributes.. 
     if (attribute is DropDownListAttribute) { 
    DropDownListAttribute dropdownAttrib = (DropDownListAttribute)attribute; 
     Console.WriteLine("table set in attribute: " + dropdownAttrib.myTable); 
     } 
    } 
} 
+0

답장을 보내 주셔서 감사합니다. 이 코드는 실제로 어디에 있습니까? 나는 이것을 Kazi가 제안한 메타 데이터 제작자 (metadataprovider)와 통합하는 방법을 볼 수 없다. 또한 인스턴스를 반영하는 것으로 보이지 않으므로 Categories 속성에서 컬렉션을 가져올 수 있습니다. – madcapnmckay

+0

사용자 지정 특성은 개체의 데코레이터이며 해당 정보는 컴파일러에서 생성 한 개체의 메타 데이터에 추가됩니다. 따라서 기본적으로 DropDownList 특성을 사용하여 범주 속성을 꾸밀 때 템플릿을 렌더링하는 동안 드롭 다운 목록으로 렌더링해야하는지 여부를 결정할 수 있습니다. –

관련 문제