在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 = "";
还是别的什么?
当前回答
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 ;-)
其他回答
我更喜欢字符串而不是字符串。选择字符串。空而不是“”是选择一个并坚持下去的问题。使用字符串的优点。空是很明显你的意思,你不会不小心复制了不可打印的字符,如“\x003”在你的“”。
使用您和您的团队认为最易读的内容。
其他答案表明,每次使用""都会创建一个新的字符串。这是不正确的-由于字符串实习,它将在每个程序集或每个AppDomain创建一次(或可能在整个过程中创建一次-在这方面不确定)。这种差异可以忽略不计——非常非常微不足道。
然而,你觉得哪个更有可读性是另一回事。这是主观的,因人而异——所以我建议你找出你的团队中大多数人喜欢什么,然后保持一致。我个人觉得“”更容易读。
“”和“”很容易被误认为彼此的论点并不能真正让我接受。除非你使用的是比例字体(我从未与任何使用比例字体的开发人员合作过),否则很容易看出区别。
没有人提到在VisualStudio中字符串的颜色编码与字符串不同。这对可读性很重要。此外,小写通常用于变量和类型,不是什么大问题,而是字符串。Empty是常量,而不是变量或类型。
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 ;-)
这完全是一个代码风格的偏好,就像。net如何处理字符串一样。然而,以下是我的观点:
我总是使用BCL类型名称访问静态方法,属性和字段:字符串。Empty或Int32.TryParse(…)或Double。ε
我总是在声明新实例时使用c#关键字:或者string foo = "bar";
我很少使用未声明的字符串字面量,因为我喜欢能够扫描代码,将它们组合成可重用的命名常量。编译器无论如何都会用字面量替换常量,所以这是一种避免神奇的字符串/数字,并通过名称赋予它们更多含义的方法。另外,更改值更容易。