2

私は次のコードを持っています:

public static void ProcessStep(Action action)
{
    //do something here
    if (Attribute.IsDefined(action.Method, typeof(LogAttribute)))
    {
        //do something here [1]
    }
    action();
    //do something here
}

簡単に使用するために、上記の方法を使用していくつかの同様の方法があります。例えば:

public static void ProcessStep(Action<bool> action)
{
    ProcessStep(() => action(true)); //this is only example, don't bother about hardcoded true
}

しかし、2番目の方法(上記)を使用すると、元のアクションに属性があったとしても、コード[1]は実行されません。

メソッドがラッパーのみで、基になるメソッドに属性が含まれているかどうか、およびこの属性にアクセスする方法を見つけるにはどうすればよいですか?

4

2 に答える 2

3

式ツリーを使用できると確信していますが、最も簡単な解決策は、MethodInfo 型の追加パラメーターを受け取るオーバーロードを作成し、次のように使用することです。


public static void ProcessStep(Action<bool> action) 
{ 
    ProcessStep(() => action(true), action.Method); //this is only example, don't bother about hardcoded true 
}
于 2010-03-17T11:19:29.353 に答える
0

まあ、できます(必ずしもこれが良いコードだとは思いません...

void ProcessStep<T>(T delegateParam, params object[] parameters) where T : class {
    if (!(delegateParam is Delegate)) throw new ArgumentException();
    var del = delegateParam as Delegate;
    // use del.Method here to check the original method
   if (Attribute.IsDefined(del.Method, typeof(LogAttribute)))
   {
       //do something here [1]
   }
   del.DynamicInvoke(parameters);
}

ProcessStep<Action<bool>>(action, true);
ProcessStep<Action<string, string>>(action, "Foo", "Bar")

しかし、それでは美人コンテストに勝てません。

あなたがやろうとしていることについてもう少し情報を提供できれば、役立つアドバイスを提供しやすくなります... (このページの解決策はどれも本当にかわいく見えないため)

于 2010-03-17T11:59:02.410 に答える