2014-05-22 7 views
0

이벤트에서 사용자 지정 특성을 가져올 수 있습니까? C# 이벤트에서 사용자 지정 특성 가져 오기

public class TestClass 
{ 
    [Test()] 
    public event EventHandler TestEvent; 

    public void RunTest() 
    { 
     //Get attributes from TestEvent 
    } 
} 

[AttributeUsage(AttributeTargets.Event)] 
public class TestAttribute : Attribute 
{ 

} 

나는 다음과 같은 시도했지만 모두 어떤 결과를 산출하지 :

Console.WriteLine("Attr: {0}", Attribute.GetCustomAttribute(TestEvent.GetMethodInfo(), typeof (TestAttribute)) != null); 
Console.WriteLine("Attr: {0}", Attribute.GetCustomAttribute(TestEvent.Method, typeof (TestAttribute)) != null); 

답변

1

이벤트는 위임의 특별한 종류, 이벤트 핸들러가 아닌 이벤트가 지정을 참조하고있는 .Method 때문에 그 자체로 이벤트에 첨부 된 속성이 아닙니다. 대신 GetEvent 메서드를 사용하여 클래스 자체의 반사를 통해 이벤트를 참조 할 수 있습니다

Console.WriteLine("Attr: {0}", 
    Attribute.GetCustomAttribute(
     typeof(TestClass).GetEvent("TestEvent"), // This line looks up the reflection of your event 
     typeof (TestAttribute)) 
    != null); 
관련 문제