2

我有一个基于

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);
}
4

2 回答 2

1

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

于 2009-12-21T23:18:29.607 回答
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);
    }
}
于 2013-10-01T14:05:59.800 回答