在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 = "";
还是别的什么?
当前回答
我个人更喜欢“”,除非有很好的理由去做更复杂的事情。
其他回答
没有人提到在VisualStudio中字符串的颜色编码与字符串不同。这对可读性很重要。此外,小写通常用于变量和类型,不是什么大问题,而是字符串。Empty是常量,而不是变量或类型。
以上任何一种。
还有很多很多更好的事情可以指手画脚。比如什么颜色的树皮最适合一棵树,我认为是模糊的棕色和淡淡的苔藓。
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变量,区别就会显现出来。为空或带双引号。
在初始化字符串的情况下。空,然后编译器警告
CS0219 - The variable 'x' is assigned but its value is never used
永远不会触发,而在使用双引号初始化的情况下,您将获得预期的消息。
这种行为在Connect文章中有解释,链接:https://connect.microsoft.com/VisualStudio/feedback/details/799810/c-warning-cs0219-not-reported-when-assign-non-constant-value
基本上,如果我做对了,他们希望允许程序员用函数的返回值设置一个变量用于调试目的,而不用警告消息来打扰他,因此他们只在常量赋值和字符串的情况下限制警告。空不是常数,而是场。
几年后 微软已经关闭了https://connect .microsoft.com网站,因此没有更多可用的讨论。然而,这篇文章https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0219有一个有趣的评论,似乎证实了前面的原因:
只有当变量值为a时,编译器才会生成此警告 编译时常量。指定一个非常量表达式或方法 结果的局部变量,使观察这些更容易 调试器中的表达式。它还使结果可达, 在该变量可达时防止垃圾收集。
我只是在看一些代码,然后这个问题突然出现在我的脑海里,这个问题是我以前读过的。这当然是可读性的问题。
考虑下面的c#代码…
(customer == null) ? "" : customer.Name
vs
(customer == null) ? string.empty : customer.Name
我个人认为后者不那么模棱两可,也更容易阅读。
正如其他人指出的那样,实际的差异可以忽略不计。