代码之家  ›  专栏  ›  技术社区  ›  Dewfy

如何区分泛型中的methodbase

  •  2
  • Dewfy  · 技术社区  · 15 年前

    我有一个基于

    Dictionary<MethodBase, string>
    

    该键从methodbase.getcurrentMethod呈现。在明确声明方法之前,一切都很好。但有一天,似乎:

    Method1<T>(string value)
    

    当t得到完全不同的类型时,在字典中生成相同的条目。

    所以我的问题是如何更好地缓存泛型方法的值。(当然,我可以提供提供getcache和equality的包装器,但这种方式看起来并不优雅)。

    更新 我真正想要的是:

    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 回复  |  直到 11 年前
        1
  •  1
  •   Ryszard Dżegan    11 年前

    使用 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);
        }
    }
    
        2
  •  1
  •   kvb    15 年前

    这是不可能的;一个泛型方法只有一个methodbase;它没有每个泛型参数集一个methodbase。