The safest way to get Invoke MethodInfo from Action <T> Instance
I am currently working on an extension method that facilitates what the title of the question suggests.
I could, of course. use the GetMetohd ("Invoke") method method for the type and execute it, But something tells me that this is not the "safest" way. Classes and types may vary, including in BCL.So, I came up with the following LINQ statement that works 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 fact is that even this seems a little inconvenient, because once an action can change and contain another method with such features. Even if I add a HasGenericParameters restriction, there is no security guarantee.
Do you have any ideas on how to get the exact instance of MethodInfo related to
"Action<T>.Invoke()" If I do not understand your intention, this whole approach seems unnecessary. You can get MethodInfo for the exact method for the delegate as follows:
Action<Foo> myAction = //get delegate... MethodInfo theMethod = myAction.Method; If an Action<T> wrapped around a specific instance method, that instance is accessible from the myAction.Target property.