Console.Writeline基础知识 [英] Console.Writeline basics

查看:197
本文介绍了Console.Writeline基础知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于下面的代码问题:

 类的currentdate 
{
静态无效的主要()
{
Console.WriteLine(DateTime.Now);
}
}



文件说:




使用指定的格式信息,将指定对象数组,
后跟当前行终止符的文本表示,标准输出流




所以我的问题是:如何来的WriteLine 知道的文本表示的DateTime 对象吗?我的意思是,如果我从我自己的类创建自己的对象,怎么会知道如何转换价值的文本?而更,它是如何知道这个值是什么?你如何定义对象的价值?


解决方案

怎么来的WriteLine知道该文本表示DateTime对象的?我的意思是,如果我从我自己的类创建自己的对象,怎么会知道如何转换价值的文本?




Console.WriteLine 拥有的set 的匹配特定类型(主要是原语)。如果编译器不会过载与所提供的类型相匹配,它与过载服用 System.Object的(授予您提供一个参数)相匹配。如果出现这种情况,它会检查,看看是否类型实现了 IFormattable ,如果是这样,它调用的IFormattable.ToString(null,格式化) 。如果没有,它调用的ToString 的对象。 的ToString System.Object的,它的所有对象继承定义。想要一个自定义的表示每个对象覆盖缺省行为,如的DateTime 一样。



举例来说,假设你有一个酒吧字符串属性类,并且希望 Console.WriteLine 通过你的来它时打印一些有意义的:

 公共类Foo 
{
公共字符串酒吧{搞定;组; }
公共重写字符串的ToString()
{
返回酒吧;
}
}



现在我们想通过它 Console.WriteLine

 公共静态无效的主要(字串[] args)
{
无功富=新富{吧=酒吧};
Console.WriteLine(富);
}



会产生栏。


I have a question about the following code:

class CurrentDate
    {
        static void Main()
        {
            Console.WriteLine(DateTime.Now);
        }
    }

Documentation says:

Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information.

So my question is: How come WriteLine knows the text representation of DateTime object? I mean, if I create my own object from my own class, how would it know how to convert the value to text? And even more, how does it know what the value is? How can you define "value" of an object?

解决方案

How come WriteLine knows the text representation of DateTime object? I mean, if I create my own object from my own class, how would it know how to convert the value to text?

Console.WriteLine has a set of overloads matching specific types (mainly primitives). If the compiler doesn't match an overload with the provided type, it matches with the overload taking System.Object (granted you provide a single parameter). If that happens, it checks to see if the type implements IFormattable, if it does, it invokes IFormattable.ToString(null, Formatter). If it doesn't, it invokes ToString on your object. ToString is defined in System.Object , which all objects inherit from. Every object that wants a custom representation overrides the default behavior, like DateTime does.

For example, lets say you have a Foo class with a Bar string property, and you want Console.WriteLine to print something meaningful when passing your Foo to it:

public class Foo
{
    public string Bar { get; set; }
    public override string ToString()
    {
         return Bar;
    }
}

And now we want to pass it Console.WriteLine:

public static void Main(string[] args)
{
      var foo = new Foo { Bar = "bar" };
      Console.WriteLine(foo);
}

Would yield "bar".

这篇关于Console.Writeline基础知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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