Detect generic parameters of MethodBase

170 views Asked by At

This question is continue of How to distinguish MethodBase in generics

In brief: I need to distinguish in Dictionary same generic method when it is called for different generic types substitution.

static Dictionary<MethodBase, string> cache = new Dictionary<MethodBase, string>();
static void Method1<T>(T g) 
{
    MethodBase m1 = MethodBase.GetCurrentMethod();
    cache[m1] = "m1:" + typeof(T);
}

So, I've overrided IEqualityComparer, to compare MethodBase argument by argument. And during debuging I was wondered that there is no way to detect real type of argument of generic method, neither GetGenericArguments nor GetParameters don't provide real type of calling. Am I right? If so I cannot see another way than compare by first line Environment.StackTrace - because only this method explores type of argument.

2

There are 2 answers

0
ironic On

I do not think that StackTrace will help you: I does not provide information about actual types with which generic was called. The most reasonable solution for me is to make your own class which will store information about generic parameters and fill it in generic methods.

Something like:

static void Method1(T g) { Helper m1 = new Helper(T.GetType()); cache[m1] = "m1:" + typeof(T); }

0
kvb On

Since a generic method has only a single MethodBase, there is no way to do what you want. You will need to use some other type as the key to your dictionary if you need this functionality, since the MethodBase alone doesn't contain the type arguments when a generic method was called.