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
}

但是当我使用第二种方法(上面的那个)时,即使原来的动作有属性,代码[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")

但这不会让你赢得选美比赛。

If you could give a little more info on what you are trying to do it would be easier to give helpful advice ... (because none of the solutions on this page look really cute)

于 2010-03-17T11:59:02.410 回答