【问题标题】:How to display the type of a custom class?如何显示自定义类的类型?
【发布时间】:2014-06-26 06:37:47
【问题描述】:

我创建了一个名为MyGenList<T> 的自定义通用列表类。我已经覆盖了ToString() 方法,因此如果列表为空,则只显示对象的类型。

public override string ToString()
    {
        if (this.count == 0)
        {
            return this.GetType().ToString();
        }
        else
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.count; i++)
            {
                sb.Append(elements[i]);
                sb.Append(System.Environment.NewLine);
            }
            return sb.ToString();
        }
    }

如果我有一个空字符列表,我希望显示GenericClasses.MyGenList&lt;char&gt;。但是,当前控制台显示GenericClasses.MyGenList1[System.Char]。你能指出我的错误吗?

【问题讨论】:

  • 如果你不想看到这个值,你为什么不硬编码呢?类型为 GenericClasses.MyGenList1[System.Char]。
  • 不,运行时类型是,设计时类型是 MyGenList,其中 T 是任何东西。 OP 希望像 C# 那样在代码语法中显示类型。
  • MyGenList&lt;List&lt;int&gt;&gt;()MyGenList&lt;Dictionary&lt;int,string&gt;&gt; 应该显示什么?

标签: c# generic-list


【解决方案1】:

试试这个:

public override string ToString()
{
    if (this.count == 0)
    {
        Type t = this.GetType();

        if (t.IsGenericType)
        {
            Type g = t.GetGenericTypeDefinition();

            return g.Name.Remove(g.Name.IndexOf('`')) + "<" + typeof(T).Name + ">";
        }

        return t.ToString();
    }
    else
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < this.count; i++)
        {
            sb.Append(elements[i]);
            sb.Append(System.Environment.NewLine);
        }
        return sb.ToString();
    }
}

【讨论】:

  • 谢谢。我认为必须有一种无需字符串操作的自动方式,但我想我错了。您的解决方案有效。
【解决方案2】:

GenericClasses.MyGenList&lt;char&gt; 是您在代码中看到的方式,GenericClasses.MyGenList1[System.Char] 然而是内部表示。

您可以在您的类上重载 ToString() 方法以按照您想要的方式显示它。

【讨论】:

    【解决方案3】:

    为此,您需要替换特殊的 ` 字符并将类型名称缩短为其 C# 等效项。

    以下代码是从此处的另一个答案复制而来的:Get user-friendly name for generic type in C#

    public static string GetFriendlyName(this Type type)
    {
        if (type == typeof(int))
            return "int";
        else if (type == typeof(short))
            return "short";
        else if (type == typeof(byte))
            return "byte";
        else if (type == typeof(bool))
            return "bool";
        else if (type == typeof(long))
            return "long";
        else if (type == typeof(float))
            return "float";
        else if (type == typeof(double))
            return "double";
        else if (type == typeof(decimal))
            return "decimal";
        else if (type == typeof(string))
            return "string";
        else if (type.IsGenericType)
            return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x))) + ">";
        else
            return type.Name;
    }
    

    它是一个扩展方法,所以它必须放在一个静态类中,可能叫做TypeExt

    你这样称呼它(根据你的代码):

    return this.GetType().GetFriendlyName();
    

    【讨论】:

      【解决方案4】:

      试试这个:

      public override string ToString()
      {
          if (this.count == 0)
          {
              var type = this.GetType().ToString();
              var matches = Regex.Matches(type,
                      @"([a-zA-Z0-9`]*\.{1}[a-zA-Z0-9`]*)*")
                      .Cast<Match>();
              foreach (Match match in matches.Where(m => m.Value != ""))
              {
                  var currentType = Type.GetType(match.Value) 
                      ?? Type.GetType(match.Value + "<>");
                  type = type.Replace(match.Value, currentType.Name);
              }
              type = type.Replace("`", "");
              return type;
          }
          else
          {
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < this.Count; i++)
              {
                  sb.Append(this[i]);
                  sb.Append(System.Environment.NewLine);
              }
              return sb.ToString();
          }
      }
      

      测试它:

      var list = new MyGenList<Dictionary<string,Dictionary<int, List<DateTime>>>>();
      Console.WriteLine(list.ToString());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-26
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多