c# - Console.WriteLine() 如何知道如何将对象转换为字符串

标签 c# console-application

我正在关注 Preamble: what is a reference type?它解释了作为值或引用类型传递的参数。第一个示例具有以下代码:

using System;
using System.Text;

public class Example1
{
    public static void Main (string[] args)
    {
        StringBuilder first = new StringBuilder();
        StringBuilder second = first;
        first.Append ("hello");
        first = null;
        Console.WriteLine (second);
    }
}

而且它没有提供StringBuilder类(或结构)的源代码,我不知道Console.WriteLine(second)是如何通过标识符返回一个字符串值的。是否可以在构造函数中返回一个值?

我尝试通过以下方式编写类或结构(但它不起作用):

struct StringBuilder
{
    private string _myString;
    public string StringBuilder
    {
        get { return _myString; }
        set { _myString = value; }
    }
    public void Append(string str)
    {
        _myString = str;
    }
}

最佳答案

看看documentation对于 Console.WriteLine(对象值)。它是这样说的:

the ToString method of value is called to produce its string representation, and the resulting string is written to the standard output stream.

所以(正如其他人所写),如果你想打印你自己的类或结构的字符串表示,你应该覆盖 ToString()方法。

关于c# - Console.WriteLine() 如何知道如何将对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8709127/

相关文章:

c# - TransactionScope 未在 MSTest 测试中回滚

c# - 如何在 C#/.NET 中创建内存泄漏

c# - 在控制台应用程序中创建图像或位图 - 似乎无法找到 System.Drawing?

c# - 是否可以在 Windows 控制台应用程序中使用 savefiledialog()

c# - 目录树的倒数第二层

c# - 将项目添加到列表然后列表出现在组合框中

c# - 显示 C# 1 数据类型的通用等效项的表格

c# - 在控制台应用程序中将范围 ({) 写入字符串

c - 在可移植 C 中将标准输出移出控制台

c# - 自托管 .NET Core 控制台应用程序中的 Startup.cs