我有一个基于的缓存
Dictionary<MethodBase, string>
密钥是从 MethodBase.GetCurrentMethod 呈现的。在显式声明方法之前,一切都工作正常。但有一天,出现了这样的情况:
Method1<T>(string value)
当 T 获得完全不同的类型时,在字典中生成相同的条目。
所以我的问题是关于缓存泛型方法的值的更好方法。 (当然我可以提供提供 GetCache 和相等遇到泛型类型的包装器,但这种方式看起来不太优雅)。
Update这就是我真正想要的:
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);
}
Use 生成通用方法, 如果可以的话:
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)