Get user-friendly name for generic type in C#

前端 未结 5 1598
自闭症患者
自闭症患者 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:18

    Based on your edited question, you want something like this:

    public static string GetFriendlyName(this Type type)
    {
        if (type == typeof(int))
            return "int";
        else if (type == typeof(short))
            return "short";
        else if (type == typeof(byte))
            return "byte";
        else if (type == typeof(bool)) 
            return "bool";
        else if (type == typeof(long))
            return "long";
        else if (type == typeof(float))
            return "float";
        else if (type == typeof(double))
            return "double";
        else if (type == typeof(decimal))
            return "decimal";
        else if (type == typeof(string))
            return "string";
        else if (type.IsGenericType)
            return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x)).ToArray()) + ">";
        else
            return type.Name;
    }
    

提交回复
热议问题