Get the type name

后端 未结 10 841
星月不相逢
星月不相逢 2020-12-05 23:05

How i can get full right name of generic type?

For example: This code

typeof(List).Name

return

10条回答
  •  情深已故
    2020-12-05 23:51

    You could use this:

    public static string GetTypeName(Type t) {
      if (!t.IsGenericType) return t.Name;
      if (t.IsNested && t.DeclaringType.IsGenericType) throw new NotImplementedException();
      string txt = t.Name.Substring(0, t.Name.IndexOf('`')) + "<";
      int cnt = 0;
      foreach (Type arg in t.GetGenericArguments()) {
        if (cnt > 0) txt += ", ";
        txt += GetTypeName(arg);
        cnt++;
      }
      return txt + ">";
    }
    

    For example:

    static void Main(string[] args) {
      var obj = new Dictionary, int>>();
      string s = GetTypeName(obj.GetType());
      Console.WriteLine(s);
      Console.ReadLine();
    }
    

    Output:

    Dictionary, Int32>>
    

提交回复
热议问题