How to distinguish MethodBase in generics

I have a cache based on

Dictionary<MethodBase, string> 

The key is displayed from the MethodBase.GetCurrentMethod method. Everything worked fine until the methods were explicitly declared. But once it turned out that:

 Method1<T>(string value) 

Makes the same entry in the dictionary when T gets completely different types.

So my question is about the best way to cache values ​​for common methods. (Of course, I can provide a wrapper that provides GetCache and the equality found in common types, but this method does not look elegant).

Update Here's what I definitely want:

 static Dictionary<MethodBase, string> cache = new Dictionary<MethodBase, string>(); static void Method1<T>(T g) { MethodBase m1 = MethodBase.GetCurrentMethod(); cache[m1] = "m1:" + typeof(T); } public static void Main(string[] args) { Method1("qwe"); Method1<Stream>(null); Console.WriteLine("===Here MUST be exactly 2 entry, but only 1 appears=="); foreach(KeyValuePair<MethodBase, string> kv in cache) Console.WriteLine("{0}--{1}", kv.Key, kv.Value); } 
+2
source share
2 answers

Use MakeGenericMethod if you can:

 using System; using System.Collections.Generic; using System.Reflection; class Program { static Dictionary<MethodBase, string> cache = new Dictionary<MethodBase, string>(); static void Main() { Method1(default(int)); Method1(default(string)); Console.ReadLine(); } static void Method1<T>(T g) { var m1 = (MethodInfo)MethodBase.GetCurrentMethod(); var genericM1 = m1.MakeGenericMethod(typeof(T)); // <-- This distinguishes the generic types cache[genericM1] = "m1:" + typeof(T); } } 
+1
source

It's impossible; the general method has a single MethodBase; it does not have one method database for a set of common arguments.

+1
source

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


All Articles