我正在关注 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/