在C#中访问包装的方法属性

时间:2010-03-17 10:47:45

标签: c# attributes custom-attributes

我有以下代码:

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

如何找到方法只是包装器,底层方法是否包含属性以及如何访问此属性?

2 个答案:

答案 0 :(得分:3)

虽然我确信你可以使用表达式树,但最简单的解决方案是创建一个带有MethodInfo类型的附加参数的重载,并像这样使用它:


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

答案 1 :(得分: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")

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

如果您可以提供更多关于您要做什么的信息,那么提供有用的建议会更容易......(因为此页面上没有任何解决方案看起来很可爱)