【问题标题】:What interface or method should my class implement to print what I want in Console.WriteLine?我的类应该实现什么接口或方法来在 Console.WriteLine 中打印我想要的内容?
【发布时间】:2008-10-09 18:40:48
【问题描述】:

我有一个 F 类的对象。我想使用 Console.WriteLine 输出对象的内容,以便像这样进行快速和肮脏的状态更新:

Console.WriteLine(objectF);

这只会将类的名称打印到控制台:

F

我想以某种方式重载它,以便打印出一些关于对象及其属性的有用信息。

我已经有一个解决方法:在我的类中重载 ToString 方法,然后调用: Console.WriteLine(objectF.ToString());

但我宁愿使用更简单的语法。有什么想法吗?

【问题讨论】:

    标签: c# .net console-application console.writeline


    【解决方案1】:

    Console.WriteLine(objectF)

    应该可以工作,如果你重载了ToString。当框架需要将对象转换为字符串表示时,它会调用ToString

    public override string ToString()
    {
        // replace the line below with your code
        return base.ToString();
    }
    

    【讨论】:

      【解决方案2】:

      您应该重写 ToString(),尽管在某些情况下您可能会发现以下代码很有用:

      public static class ObjectUtility
      {
          public static string ToDebug(this object obj)
          {
              if (obj == null)
                  return "<null>";
      
              var type = obj.GetType();
              var props = type.GetProperties();
      
              var sb = new StringBuilder(props.Length * 20 + type.Name.Length);
              sb.Append(type.Name);
              sb.Append("\r\n");
      
              foreach (var property in props)
              {
                  if (!property.CanRead)
                      continue;
                  // AppendFormat defeats the point
                  sb.Append(property.Name);
                  sb.Append(": ");
                  sb.Append(property.GetValue(obj, null));
                  sb.Append("\r\n");
              }
      
              return sb.ToString();
          }
      }
      

      用法是简单地包含包含 ObjectUtility 的命名空间,然后...

      var f = new F();
      Console.WriteLine(f.ToDebug());
      

      上面的反射用法对于高性能代码不是很好,所以不要在需要高性能的生产场景中使用它。

      【讨论】:

        【解决方案3】:

        我会继续使用 ToString()。这就是它存在的目的。另外,除非你有格式字符串,否则你可以写:

        Console.WriteLine(objectF)
        

        【讨论】:

          【解决方案4】:

          我找到了问题的原因。我忽略了将 ToString() 的实现定义为 override。正确的语法是:

          public override string ToString()
          {
             ///Do stuff...
             return string;
          }
          

          感谢下面的海报让我走上正轨

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-06-29
            • 2011-01-24
            • 2011-02-25
            • 2010-09-17
            • 2017-09-13
            • 2022-12-02
            • 2016-01-14
            相关资源
            最近更新 更多