简体   繁体   English

.ToString()和+“”之间有什么区别

[英]What's the differences between .ToString() and + “”

If I have a DateTime, and I do : 如果我有一个DateTime,我会:

date.Year.ToString()

I get the Year as String. 我把年份作为字符串。 But Also if I do 但是,如果我这样做

date.Year + ""

the differences is only that the second one doesnt get an exception if there isn't the Date? 差异只是如果没有日期,第二个不会得到例外? (which i prefeer) (我先发制人)

When you write date.Year + "" it will be compiled as a call to string.Concat(object, object) : 当你写date.Year + ""它将被编译为对string.Concat(object, object)的调用:

String.Concat(date.Year, "")

Internally, the Concat method will call ToString on each (non-null) object. 在内部, Concat方法将在每个(非null)对象上调用ToString

Both approaches will throw a NullReferenceException if date is null . 如果datenull则两种方法都将抛出NullReferenceException But you said date is of type DateTime . 但是你说dateDateTime类型。 DateTime is a struct and so cannot be null. DateTime是一个结构,因此不能为null。


If date is of type DateTime? 如果dateDateTime?类型DateTime? and want to return an empty string if date is null then you can use this: 并且如果date为null则想要返回一个空字符串,那么你可以使用它:

date.HasValue ? date.Value.Year.ToString() : ""
date.Year.ToString()

Won't work if date is null. 如果date为null,则无效。

date.Year + ""

Works even if year is null as binary + operator substitutes null with a empty string. 即使year为null也可以工作,因为binary +运算符用空字符串替换null。

This is what MSDN says about binary + operator concatenating two strings: 这就是MSDN所说的关于二元+运算符连接两个字符串的内容:

The binary + operator performs string concatenation when one or both operands are of type string. 当一个或两个操作数的类型为字符串时,binary +运算符执行字符串连接。 If an operand of string concatenation is null, an empty string is substituted. 如果字符串连接的操作数为null,则替换空字符串。 Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. 否则,通过调用从类型对象继承的虚拟ToString方法,将任何非字符串参数转换为其字符串表示形式。 If ToString returns null, an empty string is substituted. 如果ToString返回null,则替换空字符串。

More information on http://msdn.microsoft.com/en-us/library/aa691375%28VS.71%29.aspx 有关http://msdn.microsoft.com/en-us/library/aa691375%28VS.71%29.aspx的更多信息

There is no difference if date.Year is not null. 如果date.Year不为null,则没有区别。

In the second example the ToString() method is implicitly called on date.Year . 在第二个示例中,在date.Year上隐式调用ToString()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM