我具有基于高速缓存

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);
}
有帮助吗?

解决方案

使用 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);
    }
}

其他提示

这是不可能的;一个通用的方法有一个MethodBase;它不具有每一套通用参数之一MethodBase。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top