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()"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With