泛型类型的C#声明

mal*_*ois 3 c# generics reflection types .net-4.0

是否有可能得到一个反射获得的类型的"c#名称",如:

System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Run Code Online (Sandbox Code Playgroud)

我想得到:

List<String>
Run Code Online (Sandbox Code Playgroud)

没有拆分字符串有可能吗?例如,使用Reflection.

谢谢!

Mik*_*ron 6

不是直接的,但你可以检查类型本身来弄清楚.

public static string TypeName(Type t) {
    if (!t.IsGenericType) return t.Name;

    StringBuilder ret = new StringBuilder();
    ret.Append(t.Name).Append("<");

    bool first = true;
    foreach(var arg in t.GetGenericArguments()) {
        if (!first) ret.Append(", ");
        first = false;

        ret.Append(TypeName(arg));
    }

    ret.Append(">");
    return ret.ToString();
}
Run Code Online (Sandbox Code Playgroud)