2009-12-21 127 views
2

区分MethodBase我已经基于如何仿制药

Dictionary<MethodBase, string> 

的关键是从MethodBase.GetCurrentMethod渲染缓存。一切工作正常,直到方法明确宣布。但有一天它出现了:

Method1<T>(string value) 

当T得到完全不同的类型时,在Dictionary中进行相同的输入。

所以我的问题是更好的方法来缓存通用方法的值。 (当然,我可以提供提供GetCache的包装器,并且遇到泛型类型的等式,但这种方式看起来并不优雅)。

更新 这里我到底要:

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); 
} 
+0

你要为每一组的类型参数或者为每个物理块代码(我的答案)的不同高速缓存条目的不同缓存条目? – SLaks 2009-12-21 14:44:13

+1

这似乎是不可能的。 – SLaks 2009-12-21 16:05:47

回答

1

使用MakeGenericMethod,如果可以的话:

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); 
    } 
} 
+0

这是一个非常古老的问题,但我花了一些时间来评估它。看起来非常好! – Dewfy 2013-10-01 15:12:57

1

这是不可能的;一个泛型方法只有一个MethodBase;它没有每个通用参数集有一个MethodBase。