我有以下代码:

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]将不被执行。

我怎么能找到,如果方法仅仅是包装和基本方法中包含的属性以及如何访问这个属性?

有帮助吗?

解决方案

虽然我敢肯定,你可以使用表达式目录树,最简单的解决办法是只创建一个重载需要一个类型的MethodInfo的附加参数,并使用它是这样的:


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

其他提示

好了,你可以这样做(的我并不认为这是很好的代码... 的)

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")

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

如果你能给出你正在试图做到这一点会更容易得到有用的建议,一点点的详细信息...(因为没有解决方案,在这个页面看起来很可爱)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top