prostynick
prostynick

Reputation: 6219

Accessing wrapped method attribute in C#

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?

Upvotes: 2

Views: 459

Answers (2)

dalo
dalo

Reputation: 458

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)

Upvotes: 0

Henrik
Henrik

Reputation: 23324

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 
}

Upvotes: 3

Related Questions