Console.Writeline基础知识 [英] Console.Writeline basics
问题描述
我有一个关于下面的代码问题:
类的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 ofDateTime
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 takingSystem.Object
(granted you provide a single parameter). If that happens, it checks to see if the type implementsIFormattable
, if it does, it invokesIFormattable.ToString(null, Formatter)
. If it doesn't, it invokesToString
on your object.ToString
is defined inSystem.Object
, which all objects inherit from. Every object that wants a custom representation overrides the default behavior, likeDateTime
does.For example, lets say you have a
Foo
class with aBar
string property, and you wantConsole.WriteLine
to print something meaningful when passing yourFoo
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屋!