C# Get Generic Type Name

前端 未结 9 1720
旧时难觅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 06:45

    Here is my take on this. I did not put the backtick check since for what I see, it's always there. You can add it if you want but I like to keep things simple.

    public static string GetFriendlyName(this Type type)
    {
        if (type.IsGenericType)
        {
            var name = type.Name.Substring(0, type.Name.IndexOf('`'));
            var types = string.Join(",", type.GetGenericArguments().Select(GetFriendlyName));
            return $"{name}<{types}>";
        }
        else
        {
            return type.Name;
        }
    }
    

提交回复
热议问题