2011-02-08 12 views
5

誰かがクラスに反映させてそのDeprecatedメソッドを見つけるためのコードを書いているのが不思議ですか?Reflectionを使用して廃止予定を見つける

IveはT4テンプレートを有効にしていましたが、廃止予定のイベントのハンドラーの生成を止めたいと思っています。

+0

T4で反射を使用していますか?これは推奨されません(http://www.olegsych.com/2007/12/how-to-use-t4-to-generate-decorator-classes/)。 – Ani

+0

Obsoleteとマークされたメンバー(反応フレームワークの一部) – RQDQ

+0

T4テンプレートを変更してUIデリゲートのObservableを生成し、Deprecatedイベントを取得しました。 –

答えて

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); 
      } 
     } 
    } 
} 
+1

完璧、ありがとう。 –

+0

ようこそ。 – HuseyinUslu

+5

ところで、GetCustomAttributes()はオーバーロードされ、型パラメータをとることができます。したがって、メソッドが非推奨であるかどうかを調べるには、 'typeof(ObsoleteAttribute)'を渡すだけです。私が使用しているチェッカー(enum値の場合)は: 'return obj.GetType()。GetField(obj.ToString())。GetCustomAttributes(typeof(System.ObsoleteAttribute)、true).Length> 0;' – piojo

関連する問題