2009-12-01 5 views
1

기본 클래스의 메서드에서 클래스의 사용자 지정 특성을 검색 할 수 있어야합니다. 지금 나는 다음과 같은 구현 기본 클래스에서 보호 정적 메소드를 통해 그 일을하고있다 (클래스 적용 동일한 속성의 여러 인스턴스를 가질 수) :기본 클래스에서 GetCustomAttributes를 호출하려면 어떻게해야합니까?

//Defined in a 'Base' class 
protected static CustomAttribute GetCustomAttribute(int n) 
{ 
     return new StackFrame(1, false) //get the previous frame in the stack 
             //and thus the previous method. 
      .GetMethod() 
      .DeclaringType 
      .GetCustomAttributes(typeof(CustomAttribute), false) 
      .Select(o => (CustomAttribute)o).ToList()[n]; 
} 

을 내가 thusly 히 파생 클래스에서 호출 :

[CustomAttribute] 
[CustomAttribute] 
[CustomAttribute] 
class Derived: Base 
{ 
    static void Main(string[] args) 
    { 

     var attribute = GetCustomAttribute(2); 

    } 

} 

이상적으로 저는 이것을 생성자에서 호출하고 결과를 캐시 할 수 있습니다.

감사합니다.

내가 해당 GetCustomAttributes 어휘 순서와 관련하여이를 반환 보장되지 않는다는 것을 깨닫게 PS

.

답변

8

정적 메서드 대신 인스턴스 메서드를 사용한 경우에는 기본 클래스에서 this.GetType()을 호출 할 수 있습니다.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
class CustomAttribute : Attribute 
{} 

abstract class Base 
{ 
    protected Base() 
    { 
     this.Attributes = Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute)) 
      .Cast<CustomAttribute>() 
      .ToArray(); 
    } 

    protected CustomAttribute[] Attributes { get; private set; } 
} 

[Custom] 
[Custom] 
[Custom] 
class Derived : Base 
{ 
    static void Main() 
    { 
     var derived = new Derived(); 
     var attribute = derived.Attributes[2]; 
    } 
} 

더 간단하고 원하는 생성자에서 캐싱을 수행합니다.

+0

감사합니다. 그것은 좋은 일이지만 싱글 톤을 위해 작동하려면이 기능이 필요합니다. 스택 프레임을 보면 해킹 된 느낌이 들지만 API를 깨끗하게 유지하므로 지금 당장 사용하겠습니다. 나는 다른 사람들을 도울 수 있기 때문에 당신의 대답을 받아 들였습니다. –

관련 문제