在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 = "";
还是别的什么?
当前回答
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.
其他回答
我没有什么区别。最后一个是打字最快的:)
我用的是第三个,但在其他两个中,第一个似乎没那么奇怪。 string是string的别名,但在赋值中看到它们会让人感觉不舒服。
我认为第二个是“合适的”,但老实说,我不认为这有什么关系。编译器应该足够聪明,可以将其中任何一个编译为完全相同的字节码。我用“myself”。
字符串。空和字符串。空的是等价的。String是BCL类名;字符串是它的c#别名(或快捷方式,如果你愿意)。与Int32和int相同。更多示例请参见文档。
至于“”,我不太确定。
就我个人而言,我总是使用string.Empty。
字符串是System的同义词。字符串类型,它们是相同的。
值也是相同的:字符串。空==字符串。空== ""
我不会在代码中使用字符常量“”,而是字符串。空或字符串。空-更容易看到程序员的意思。
在字符串和字符串之间,我更喜欢小写字符串,因为我曾经使用Delphi很多年,Delphi风格是小写字符串。
所以,如果我是你的老板,你会写字符串。空