How to distinguish MethodBase in generics

前端 未结 2 576
旧巷少年郎
旧巷少年郎 2021-01-23 06:12

I have a cache based on

Dictionary

The key is rendered from MethodBase.GetCurrentMethod. Everything worked fine unti

相关标签:
2条回答
  • 2021-01-23 06:45

    Use MakeGenericMethod, if you can:

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-23 06:59

    This is not possible; a generic method has a single MethodBase; it doesn't have one MethodBase per set of generic arguments.

    0 讨论(0)
提交回复
热议问题