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

C# 在C语言中访问包装方法属性#,c#,attributes,custom-attributes,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 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
}
publicstaticvoidprocessstep(操作)
{
ProcessStep(()=>action(true));//这只是一个示例,不必担心硬编码的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 
}

公共静态无效处理步骤(操作)
{ 
ProcessStep(()=>action(true),action.Method);//这只是一个示例,不要担心硬编码的true
}
好吧,你可以这样做(我不一定认为这是好代码…)

void ProcessStep(T delegateParam,params object[]参数),其中T:class{
如果(!(delegateParam为Delegate))抛出新的ArgumentException();
var del=作为委托的delegateParam;
//在这里使用del.Method检查原始方法
if(Attribute.IsDefined(del.Method,typeof(LogAttribute)))
{
//在这里做点什么[1]
}
del.DynamicInvoke(参数);
}
ProcessStep(action,true);
过程步骤(动作“Foo”、“Bar”)
但这不会为你赢得选美比赛


如果你能提供更多关于你正在尝试做的事情的信息,那么给出有用的建议就更容易了。。。(因为本页上没有一个解决方案看起来很可爱)

这是另一种情况,当时我没有想到非常明显的解决方案:)谢谢:)不幸的是,我有更多类似的方法,如ProcessStep、ProcessStep、ProcessStep+TParams,现在代码看起来很难看,所以我要找到没有该属性的解决方案。
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")