[英]What interface or method should my class implement to print what I want in Console.WriteLine?
I have an object of class F. I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this: 我有一个类F的对象。我想使用Console.WriteLine输出对象的内容,以进行快速和肮脏的状态更新,如下所示:
Console.WriteLine(objectF); Console.WriteLine(objectF);
This prints out only the name of the class to the console: 这仅将类的名称输出到控制台:
F
I want to overload this somehow so that I can instead print out some useful information about the object and its properties. 我想以某种方式重载它,以便我可以打印出一些有关对象及其属性的有用信息。
I have a workaround already: To overload the ToString method in my class and then call: Console.WriteLine(objectF.ToString()); 我已经有了一个解决方法:在类中重载ToString方法,然后调用:Console.WriteLine(objectF.ToString());。
But I would rather have the simpler syntax. 但是我宁愿使用更简单的语法。 Any ideas? 有任何想法吗?
Console.WriteLine(objectF) Console.WriteLine(objectF)
Should work, if you overloaded ToString
. 如果您重载ToString
,则应该工作。 When the framework needs to convert an object to a string representation, it invokes ToString
. 当框架需要将对象转换为字符串表示形式时,它将调用ToString
。
public override string ToString()
{
// replace the line below with your code
return base.ToString();
}
You should override ToString() though in some situations you may just find the following code useful: 您应该重写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();
}
}
Usage is to simply include the namespace containing ObjectUtility and then... 用法是仅包含包含ObjectUtility的名称空间,然后...
var f = new F();
Console.WriteLine(f.ToDebug());
The reflection usage above isn't very good for high performance code so don't use it in a production scenario where high performance is desired. 上面的反射用法对高性能代码不是很好,因此请不要在需要高性能的生产场景中使用它。
I would continue to use ToString(). 我将继续使用ToString()。 That's its purpose for existing. 这就是现有的目的。 Also, unless you have a format string, you can just write: 另外,除非您有格式字符串,否则只需编写以下内容:
Console.WriteLine(objectF)
I found the cause of my problem. 我找到了问题的原因。 I had neglected to define my implementation of ToString() as an override . 我忽略了将ToString()的实现定义为重写 。 The correct syntax is: 正确的语法是:
public override string ToString()
{
///Do stuff...
return string;
}
Thanks to the posters below who put me on the right track 感谢下面的海报使我走上正轨
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.