我有一个基于
Dictionary<MethodBase, string>密钥是从MethodBase.GetCurrentMethod呈现的。在方法显式声明之前,一切都很好。但有一天似乎:
Method1<T>(string value)当T得到完全不同的类型时,在字典中输入相同的条目。
因此,我的问题是如何更好地缓存泛型方法的值。(当然,我可以提供包装器,它提供了遇到泛型类型的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);
}发布于 2013-10-01 14:05:59
如果可以的话,可以使用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);
}
}发布于 2009-12-21 23:18:29
这是不可能的;泛型方法只有一个MethodBase;每个泛型参数集没有一个MethodBase。
https://stackoverflow.com/questions/1940436
复制相似问题