如何获取包含泛型参数的Type.Name?

时间:2011-05-08 17:55:06

标签: .net reflection

new List<int>().GetType().Name是List`1。如何获得更像List<int>的名称( List<T>)?

2 个答案:

答案 0 :(得分:2)

一种方法是使用new List<int>().GetType().ToString(),返回System.Collections.Generic.List`1[System.Int32]

或者你可以写下一个小帮手方法:

string GetShortName(Type type)
{
    string result = type.Name;
    if (type.IsGenericType)
    {
        // remove genric indication (e.g. `1)
        result = result.Substring(0, result.LastIndexOf('`'));

        result = string.Format(
            "{0}<{1}>",
            result,
            string.Join(", ",
                        type.GetGenericArguments().Select(t => GetShortName(t))));
    }

    return result;
}

输出如下字符串:

List<Int32>
List<T>
Dictionary<List<Double>, Int32>
Tuple<T1, T2, T3, T4>

请注意,对于嵌套类型,这将只返回最里面的名称。

答案 1 :(得分:0)

String.Format("{0}<{1}>",GetType().Name, typeof(T).Name) 

编辑:es在评论中指出,这在泛型类中是有用的,f.e。 to to say toString()的重载的不同的泛型类型参数。大多数情况下,查询上面的{0}第一个参数没有意义,因为它在同一个类中没有变化。所以人们也可以使用:

String.Format("List<{0}>", typeof(T).Name) 
相关问题