Get real type of generic method from StackFrame

In my registration module, I have a line:

MethodBase methodBase = new StackFrame(2, false).GetMethod();

The test method is a general method and is defined as T[] MyMethod<T>() . Is there a way to get my real type instead of T from methodBase ?

+5
source share
2 answers

As far as I know, you cannot do this. The information in the StackFrame is not retrieved from the runtime information, but from the .pdb information, matching the return address found in the stack frame with the assembly offsets described in .pdb. That is, only compilation time information is available, which, of course, is an open universal method.

Note that even if you manually create a private shared method and call it directly, you still get the public shared method from .pdb. For instance:

 class Program { static void Main(string[] args) { MethodInfo miOpen = typeof(Program).GetMethod("Method", BindingFlags.Static | BindingFlags.NonPublic), miClosed = miOpen.MakeGenericMethod(typeof(int)); Type type; object[] invokeArgs = { 17, null }; int[] rgi = (int[])miClosed.Invoke(null, invokeArgs); type = (Type)invokeArgs[1]; } static T[] Method<T>(T t, out Type type) { type = GetMethodType(); return new[] { t }; } private static Type GetMethodType() { StackFrame frame = new StackFrame(1, false); MethodBase mi = frame.GetMethod(); return mi.GetGenericArguments()[0]; } } 

In the above example, the value of the type variable assigned at the end still refers to the type {T} for the public public method, not Int32 , as you would expect in your case. This is despite the fact that the Int32 type is retrieved from the miClosed .

If you need information about a particular type, you will need to provide a mechanism in your code to explicitly define it (for example, pass the typeof(T) value to the registration component from the most common method). The StackFrame class StackFrame not have the necessary information for this.

+4
source

Use GetGenericArguments off MethodBase to get what was passed in T

-1
source

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


All Articles