如何区分泛型中的MethodBase

时间:2009-12-21 14:34:22

标签: .net generics hashcode equality 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);
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);
    }
}