Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safest way to get the Invoke MethodInfo from Action<T>'s Instance

I am currently working on an extension method that facilitates what the question's title suggests.

I could, of course. use the GetMetohd("Invoke") method call on the type and be done with it, But something tells me this is not the "safest" way to go. Classes and types may change, including those in the BCL.

So I've come up with the following LINQ statement, which works just fine:

 public static class ActionExtensions
{
    public static MethodInfo GetInvoke<T>(this Action<T> obj)
    {
        var actionType = obj.GetType();
        var tType= typeof(T);

        return (
             from methodInfo
             in actionType.GetMethods()
             let par = methodInfo.GetParameters()
             where par.Length == 1 && par[0].ParameterType == tType
             select methodInfo
             ).FirstOrDefault();
    }
}

The thing is, even this feels somewhat iffy, since one day Action can change and contain another method with such traits.. even if I add the "HasGenericParameters" constraint, there's no assurance of safety.

Do you have any ideas regarding a way to obtain the exact MethodInfo instance relevant to

"Action<T>.Invoke()"
like image 706
Eyal Perry Avatar asked Jun 18 '14 14:06

Eyal Perry


1 Answers

Unless I am misunderstanding your intent, this whole approach seems unnecessary. You can acquire the MethodInfo for the exact method behind a delegate like so:

Action<Foo> myAction = //get delegate...
MethodInfo theMethod = myAction.Method;

If the Action<T> is wrapped around a specific instance's method, that instance is available from the myAction.Target property.

like image 69
Rex M Avatar answered Nov 05 '22 15:11

Rex M