Call the universal extension method for an object?

I created a generic extension method for a DataRow object. The method takes no arguments. I want to call a Generic method through Reflection using MethodInfo. I can do this for the public Normarl methods, but for some reason I cannot get a reference to the Generic Extension method.

I read this question that somehwat relates to my query, but no luck like that.

+4
source share
1 answer

Keep in mind that extension methods are compiler tricks. If you look at the static method in the static class where the extension method is defined, you can call it just fine.

Now, if all you have is an object, and you are trying to find a specific extension method, you can find the appropriate extension method by searching for all your static classes in the application domain for methods that have System.Runtime.CompilerServices.ExtensionAttribute and The specific method name and the corresponding sequence of parameters.

This 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 uploaded to the application domain.

A simple approach is this (if you are looking for a general 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(); } } 
+11
source

Source: https://habr.com/ru/post/1286794/


All Articles