Get the type name

后端 未结 10 865
星月不相逢
星月不相逢 2020-12-05 23:05

How i can get full right name of generic type?

For example: This code

typeof(List).Name

return

10条回答
  •  忘掉有多难
    2020-12-05 23:40

    Another way to get a nice type name by using an extension:

    typeof(Dictionary>>).CSharpName();
    // output is: 
    // Dictionary>>
    

    The Extension Code:

    public static class TypeExtensions
    {
       public static string CSharpName(this Type type)
       {
           string typeName = type.Name;
    
           if (type.IsGenericType)
           {
               var genArgs = type.GetGenericArguments();
    
               if (genArgs.Count() > 0)
               {
                   typeName = typeName.Substring(0, typeName.Length - 2);
    
                   string args = "";
    
                   foreach (var argType in genArgs)
                   {
                       string argName = argType.Name;
    
                       if (argType.IsGenericType)
                           argName = argType.CSharpName();
    
                       args += argName + ", ";
                   }
    
                   typeName = string.Format("{0}<{1}>", typeName, args.Substring(0, args.Length - 2));
               }
           }
    
           return typeName;
       }        
    }
    

提交回复
热议问题