C# Get Generic Type Name

前端 未结 9 1729
旧时难觅i
旧时难觅i 2020-11-30 06:09

I need some way to get the Name of a Type, when type.IsGenericType = true.

    Type t = typeof(List);
    MessageBox.         


        
9条回答
  •  天命终不由人
    2020-11-30 07:11

    You can implement an extension method to get the "friendly name" of a type, like this:

    public static class TypeNameExtensions
    {
        public static string GetFriendlyName(this Type type)
        {
            string friendlyName = type.Name;
            if (type.IsGenericType)
            {
                int iBacktick = friendlyName.IndexOf('`');
                if (iBacktick > 0)
                {
                    friendlyName = friendlyName.Remove(iBacktick);
                }
                friendlyName += "<";
                Type[] typeParameters = type.GetGenericArguments();
                for (int i = 0; i < typeParameters.Length; ++i)
                {
                    string typeParamName = GetFriendlyName(typeParameters[i]);
                    friendlyName += (i == 0 ? typeParamName : "," + typeParamName);
                }
                friendlyName += ">";
            }
    
            return friendlyName;
        }
    }
    

    With this in your project, you can now say:

    MessageBox.Show(t.GetFriendlyName());
    

    And it will display "List".

    I know the OP didn't ask for the generic type parameters, but I prefer it that way. ;-)

    Namespaces, standard aliases for built-in types, and use of StringBuilder left as an exercise for the reader. ;-)

提交回复
热议问题