Is there a way to determine if a generic type is built from a specific generic type definition?

后端 未结 4 1341
忘掉有多难
忘掉有多难 2020-12-18 08:45

I\'ve got a generic method:

Func, bool> CreateFunction()

where T can be any number of diff

4条回答
  •  天涯浪人
    2020-12-18 09:17

    You could do something like

    class Program
    {
        static void Main(string[] args)
        {
            Example>.IsDictionary();
    
            Example>.IsDictionary();
    
            Example>.IsDictionary();
    
            Console.ReadKey();
        }
    }
    
    public class Example
    {
        public static void IsDictionary()
        {
            if (typeof(T).GetInterface(typeof(IDictionary<,>).Name) != null || typeof(T).Name.Contains("IDictionary"))
            {
                Console.WriteLine("Is IDictionary");
            }
            else
            {
                Console.WriteLine("Not IDictionary");
            }
        }
    }
    

提交回复
热议问题