C# declaration of generic type

后端 未结 5 979
不知归路
不知归路 2021-01-21 06:09

Is it possible to get the \"c# name\" of a type obtained with reflexion like:

System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Cultur         


        
5条回答
  •  青春惊慌失措
    2021-01-21 06:49

    Not directly, but you can examine the type itself to figure it out.

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

提交回复
热议问题