2011-02-08 38 views
5

我很好奇,如果有人寫過任何代碼以反映到類中並找到其棄用方法?使用Reflection來查找折舊

我掀起了T4模板的反應,並希望它停止生成處理程序的棄用事件,任何聰明的黑客已經打敗了我的拳頭?

+0

您是否在T4中使用反射?這是[不推薦](http://www.olegsych.com/2007/12/how-to-use-t4-to-generate-decorator-classes/)。 – Ani 2011-02-08 21:36:58

+0

你的意思是標記爲Obsolete的成員(是被動框架的一部分嗎?) – RQDQ 2011-02-08 21:37:31

回答

8

我不知道你是否要求t4框架,但這裏是一個反作用過時標記方法的反射樣本。

class TestClass 
{ 
    public TestClass() 
    { 
     DeprecatedTester.FindDeprecatedMethods(this.GetType()); 
    } 

    [Obsolete("SomeDeprecatedMethod is deprecated, use SomeNewMethod instead.")] 
    public void SomeDeprecatedMethod() { } 

    [Obsolete("YetAnotherDeprecatedMethod is deprecated, use SomeNewMethod instead.")] 
    public void YetAnotherDeprecatedMethod() { } 

    public void SomeNewMethod() { }   
} 

public class DeprecatedTester 
{ 
    public static void FindDeprecatedMethods(Type t) 
    { 
     MethodInfo[] methodInfos = t.GetMethods(); 

     foreach (MethodInfo methodInfo in methodInfos) 
     { 
      object[] attributes = methodInfo.GetCustomAttributes(false); 

      foreach (ObsoleteAttribute attribute in attributes.OfType<ObsoleteAttribute>()) 
      { 
       Console.WriteLine("Found deprecated method: {0} [{1}]", methodInfo.Name, attribute.Message); 
      } 
     } 
    } 
}