简体   繁体   English

我的类应该实现哪种接口或方法以在Console.WriteLine中打印我想要的内容?

[英]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.

相关问题 Console.WriteLine语句中的“控制台”是什么? - What is the “Console” in Console.WriteLine statements? {0} 在 Console.WriteLine 中代表什么? - What does {0} stands for in Console.WriteLine? Winforms中Console.WriteLine()的用途是什么 - What is the Purpose of Console.WriteLine() in Winforms Console.WriteLine 与打印 - Console.WriteLine vs Print Console.WriteLine($&quot;welcome{name}&quot;) 和 Console.WriteLine(&quot;welcome {0}&quot;,name) 有什么区别 - What is Difference Between Console.WriteLine($"welcome{name}") and Console.WriteLine("welcome {0}",name) Console.WriteLine(&#39;single quote&#39;)之间有什么区别? 和Console.WriteLine(“双引号”); - What is the difference between Console.WriteLine('single quote'); and Console.WriteLine(“double quote”); 在 LINQPad 中使用 Dump() 扩展方法和使用 Console.WriteLine() 有什么区别? - What is the difference between using the Dump() extension method and using the Console.WriteLine() in the LINQPad? {0}在字符串文字中(例如,在Console.WriteLine中)是什么意思? - What does {0} mean in a string literal, for example in Console.WriteLine? 在 C# 中,如何使用 Console.WriteLine 方法从我的 SqlCommand 中写入所有列 - In C#, how do I use Console.WriteLine method to write ALL columns from my SqlCommand C#指针Console.WriteLine中的X表示什么? - C# pointers what does X in the Console.WriteLine signify?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM