Get user-friendly name for generic type in C#

前端 未结 5 1605
自闭症患者
自闭症患者 2020-12-06 00:32

Is there an easy way without writing a recursive method which will give a \'user friendly\' name for a generic type from the Type class?

E.g. For the fo

5条回答
  •  忘掉有多难
    2020-12-06 01:11

    Reflection - Getting the generic parameters from a System.Type instance

    You can also use reflection on generic types:

    var dict = new Dictionary();
    
        Type type = dict.GetType();
        Console.WriteLine("Type arguments:");
        foreach (Type arg in type.GetGenericArguments())
        {
            Console.WriteLine("  {0}", arg);
        }
    

    You can then put it into some extension method for object and use it anywhere you need. I would also like to add that every recursion can be written as imperative code.

    So the whole code will look like:

     static void GetGenericParametersNames(Type type)
            {
                Queue typeQueue = new Queue();
                typeQueue.Enqueue(type);
                while (typeQueue.Any())
                {
                    var t = typeQueue.Dequeue();
                    Console.WriteLine("  {0}", arg);
    
                    foreach (Type arg in t.GetGenericArguments())
                    {
                        typeQueue.Enqueue(t);
                    }
                }
            }
    

提交回复
热议问题