在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 = "";
还是别的什么?
当前回答
字符串是System的同义词。字符串类型,它们是相同的。
值也是相同的:字符串。空==字符串。空== ""
我不会在代码中使用字符常量“”,而是字符串。空或字符串。空-更容易看到程序员的意思。
在字符串和字符串之间,我更喜欢小写字符串,因为我曾经使用Delphi很多年,Delphi风格是小写字符串。
所以,如果我是你的老板,你会写字符串。空
其他回答
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 ;-)
编译器应该让它们在长期运行时都是一样的。选择一个标准,这样你的代码就容易阅读,并坚持下去。
以上任何一种。
还有很多很多更好的事情可以指手画脚。比如什么颜色的树皮最适合一棵树,我认为是模糊的棕色和淡淡的苔藓。
这可能是一个有争议的评论,但是,总的来说,我发现当我与微软保持一致时,我的生活更容易。我们不可能知道他们做事的全部深层原因(我想有时是非常严格的,有时是笨拙的)。
他们在自动生成的文件(如Assembly文件)中使用“”,所以这就是我所做的。事实上,当我尝试用字符串替换任何下面的“”。空,Visual Studio崩溃在我身上。这可能有一个合乎逻辑的解释,但以我有限的知识,如果我只是做他们做的事情,大多数时候,事情都会解决。(反:我知道一些自动生成的文件也使用字符串。空的,这有点打破我的观点。:))
<Assembly: System.Reflection.AssemblyCulture("")>
<Assembly: System.Reflection.AssemblyDescription("")>
<Assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")>
<Assembly: System.Reflection.AssemblyKeyFile("")>
<Assembly: System.Reflection.AssemblyProduct("")>
<Assembly: System.Reflection.AssemblyTitle("")>
前两种我都可以接受。我将避免使用最后一种方法,因为在引号之间加空格很容易引入错误。这种特殊的缺陷很难通过观察发现。假设没有错别字,所有这些在语义上都是等价的。
(编辑)
另外,为了保持一致性,你可能总是想使用string或string,但这只是我的想法。