在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 = "";
还是别的什么?
当前回答
我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个using System;在你的档案里。
至于在字符串上选择“”。空,这是个人喜好,应该由你的团队决定。
其他回答
这完全是一个代码风格的偏好,就像。net如何处理字符串一样。然而,以下是我的观点:
我总是使用BCL类型名称访问静态方法,属性和字段:字符串。Empty或Int32.TryParse(…)或Double。ε
我总是在声明新实例时使用c#关键字:或者string foo = "bar";
我很少使用未声明的字符串字面量,因为我喜欢能够扫描代码,将它们组合成可重用的命名常量。编译器无论如何都会用字面量替换常量,所以这是一种避免神奇的字符串/数字,并通过名称赋予它们更多含义的方法。另外,更改值更容易。
我本来不想插嘴的,但我发现这里有一些错误的信息。
我个人更喜欢字符串。这是个人喜好,我会根据具体情况服从与我合作的任何团队的意愿。
正如其他人所提到的,字符串和字符串之间根本没有区别。Empty和String.Empty。
此外,这是一个鲜为人知的事实,使用“”是完全可以接受的。在其他环境中,“”的每个实例都将创建一个对象。然而,. net会实习它的字符串,因此未来的实例将从实习池中提取相同的不可变字符串,任何性能损失都可以忽略不计。来源:布拉德·艾布拉姆斯。
我用的是第三个,但在其他两个中,第一个似乎没那么奇怪。 string是string的别名,但在赋值中看到它们会让人感觉不舒服。
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.
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 ;-)