在c#中,我想用空字符串初始化一个字符串值。
我该怎么做呢? 什么是正确的方法,为什么?
string willi = string.Empty;
or
string willi = String.Empty;
or
string willi = "";
还是别的什么?
在c#中,我想用空字符串初始化一个字符串值。
我该怎么做呢? 什么是正确的方法,为什么?
string willi = string.Empty;
or
string willi = String.Empty;
or
string willi = "";
还是别的什么?
当前回答
我只是在看一些代码,然后这个问题突然出现在我的脑海里,这个问题是我以前读过的。这当然是可读性的问题。
考虑下面的c#代码…
(customer == null) ? "" : customer.Name
vs
(customer == null) ? string.empty : customer.Name
我个人认为后者不那么模棱两可,也更容易阅读。
正如其他人指出的那样,实际的差异可以忽略不计。
其他回答
I strongly prefer String.Empty, aside from the other reasons to ensure you know what it is and that you have not accidentally removed the contents, but primarily for internationalization. If I see a string in quotes then I always have to wonder whether that is new code and it should be put into a string table. So every time code gets changed/reviewed you need to look for "something in quotes" and yes you can filter out the empty strings but I tell people it is good practice to never put strings in quotes unless you know it won't get localized.
没有人提到在VisualStudio中字符串的颜色编码与字符串不同。这对可读性很重要。此外,小写通常用于变量和类型,不是什么大问题,而是字符串。Empty是常量,而不是变量或类型。
以上任何一种。
还有很多很多更好的事情可以指手画脚。比如什么颜色的树皮最适合一棵树,我认为是模糊的棕色和淡淡的苔藓。
我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个using System;在你的档案里。
至于在字符串上选择“”。空,这是个人喜好,应该由你的团队决定。
http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx:
As David implies, there difference between String.Empty and "" are pretty small, but there is a difference. "" actually creates an object, it will likely be pulled out of the string intern pool, but still... while String.Empty creates no object... so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code... As for System.String.Empty or string.Empty or String.Empty... my care level is low ;-)