2009-12-21 137 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。