views:

138

answers:

2

I have following code:

public static void ProcessStep(Action action)
{
    //do something here
    if (Attribute.IsDefined(action.Method, typeof(LogAttribute)))
    {
        //do something here [1]
    }
    action();
    //do something here
}

For easy use I have some similar methods using method above. For example:

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

But when I use the second method (the one above), even if original action had attribute, code [1] will not be executed.

How can I find if method is only wrapper and underlying method contains attribute and how to access this attribute?

+3  A: 

While I'm sure you could use expression trees, the easiest solution would be to just create an overload that takes an additional parameter of type MethodInfo and use it like this:


public static void ProcessStep(Action<bool> action) 
{ 
    ProcessStep(() => action(true), action.Method); //this is only example, don't bother about hardcoded true 
}
Henrik
It is another situation when I didn't thought about quite obvious solution :) Thanks :) Unfortunately I have more similar methods like ProcessStep, ProcessStep<Action>, ProcessStep<Func> + TParams, and code looks ugly now, so I am going to find solution without that attribute.
prostynick
A: 

Well, you could do (I don't necessarily think this is good code ...)

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

but that's not going to win you a beauty contest.

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)

dalo