2010-03-17 81 views
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]将不被执行。

如何才能找到方法只是包装和基础方法包含属性以及如何访问此属性?

回答

3

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


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

这是另一种情况当我没有想到相当明显的解决方案:)谢谢:)不幸的是,我有更多类似的方法,如ProcessStep,ProcessStep ,ProcessStep + TParams,现在代码看起来很丑,所以我会找到没有该属性的解决方案。 – prostynick 2010-03-17 12:55:38

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

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

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