开发者

How to get a Type.Name that includes generic parameters?

new List<int&g开发者_Python百科t;().GetType().Name is List`1. How do I get a name more like List<int> (not List<T>)?


One way would be using new List<int>().GetType().ToString(), which returns System.Collections.Generic.List`1[System.Int32].

Or you could write yourself a small helper method along the lines of:

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;
}

which outputs strings like:

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

Note that for nested types, this would return only the innermost name.


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

Edit: es pointed out in the comment, this is usefull inside a generic class, f.e. to distinct individual generic type arguments for overloads of lets say ToString(). Most the time, there is no point in querying the {0} first argument above, since it does not change in the same class. So one could just as well use:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜