Get user-friendly name for generic type in C#

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

    Building a more complete answer off of Kirk's would look like this. Modifications:

    • Support for all C# keywords
    • Supports custom-translations
    • Arrays
    • Nullables being ValueType? instead of Nullable

    Here's full code:

    public static class TypeTranslator
    {
        private static Dictionary _defaultDictionary = new Dictionary
        {
            {typeof(int), "int"},
            {typeof(uint), "uint"},
            {typeof(long), "long"},
            {typeof(ulong), "ulong"},
            {typeof(short), "short"},
            {typeof(ushort), "ushort"},
            {typeof(byte), "byte"},
            {typeof(sbyte), "sbyte"},
            {typeof(bool), "bool"},
            {typeof(float), "float"},
            {typeof(double), "double"},
            {typeof(decimal), "decimal"},
            {typeof(char), "char"},
            {typeof(string), "string"},
            {typeof(object), "object"},
            {typeof(void), "void"}
        };
    
        public static string GetFriendlyName(this Type type, Dictionary translations)
        {
            if(translations.ContainsKey(type))
                return translations[type];
            else if (type.IsArray)
            {
                var rank = type.GetArrayRank();
                var commas = rank > 1 
                    ? new string(',', rank - 1)
                    : "";
                return GetFriendlyName(type.GetElementType(), translations) + $"[{commas}]";
            }
            else if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                return type.GetGenericArguments()[0].GetFriendlyName() + "?";
            else if (type.IsGenericType)
                return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x)).ToArray()) + ">";
            else
                return type.Name;
        }
    
        public static string GetFriendlyName(this Type type)
        {
            return type.GetFriendlyName(_defaultDictionary);
        }
    }
    

提交回复
热议问题