I have created a Generic Extension method for DataRow object. The method takes no argument. I want to Invoke the Generic method through Reflection using MethodInfo. I can do this for Normarl public methods, but somehow I cannot get the reference of the Generic Extension method.
I've read this question on SO which somehwat relates to my query, but no luck that way.
Keep in mind that extension methods are compiler tricks. If you look up the static method on the static class where the extension method is defined you can invoke it just fine.
Now, if all you have is an object and you are trying to find a particular extension method you could find the extension method in question by searching all your static classes in the app domain for methods that have the System.Runtime.CompilerServices.ExtensionAttribute
and the particular method name and param sequence in question.
That approach will fail if two extension classes define an extension method with the same name and signature. It will also fail if the assembly is not loaded in the app domain.
The simple approach is this (assuming you are looking for a generic method):
static class Extensions {
public static T Echo<T>(this T obj) {
return obj;
}
}
class Program {
static void Main(string[] args) {
Console.WriteLine("hello".Echo());
var mi = typeof(Extensions).GetMethod("Echo");
var generic = mi.MakeGenericMethod(typeof(string));
Console.WriteLine(generic.Invoke(null, new object[] { "hello" }));
Console.ReadKey();
}
}
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