Console.WriteLine()怎么知道如何将对象转换为字符串 [英] How does Console.WriteLine() know how to convert an object to a string

查看:188
本文介绍了Console.WriteLine()怎么知道如何将对象转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的序言:什么是引用类型地方说明作为传递的值或引用类型的参数。第一个例子具有下面的代码:

 使用系统; 
使用System.Text;

公共类例1
{
公共静态无效的主要(字串[] args)
{
StringBuilder的第一=新的StringBuilder();
StringBuilder的第二=第一;
first.Append(你好);
第一= NULL;
Console.WriteLine(第二);
}
}

和它不提供对类的源代码的StringBuilder(或结构),我不知道Console.WriteLine命令(二)是如何能够仅仅通过使用标识符返回一个字符串值。是否有可能在构造函数返回一个值?



我试着写遵循类或结构(和它不工作):

 结构的StringBuilder 
{
私人字符串_myString;
公共字符串的StringBuilder
{
{返回_myString; }
集合{_myString =价值; }
}
公共无效追加(字符串str)
{
_myString = str中;
}
}


解决方案

有一个看起来的文档 Console.WriteLine (对象的值)。它说的:




价值的ToString 方法被调用产生的字符串
表示,并且将所得的字符串写入到标准
输出流。




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


I am following the Preamble: what is a reference type? where it explains parameters passing as value or reference type. The first example has the following code:

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);
    }
}

And it does not provide the source code for the class (or struct) of StringBuilder, and I do not know how the Console.WriteLine(second) is able to return a string value just by using the identifier. Is it possible to return a value in the constructor?

I tried to write the class or struct by following (and it doesn't work):

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

解决方案

Have a look a the documentation for Console.WriteLine(object value). It says this:

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

So (as others have written), if you want to print a string representation of your own class or struct, you should override the ToString() method.

这篇关于Console.WriteLine()怎么知道如何将对象转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆