在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 = "";
还是别的什么?
当前回答
如果你想恶作剧某人,在他们的代码中加入“”。这不是空字符串,它是“\u200D”。你不能用string.Empty欺骗别人。
其他回答
我只是在看一些代码,然后这个问题突然出现在我的脑海里,这个问题是我以前读过的。这当然是可读性的问题。
考虑下面的c#代码…
(customer == null) ? "" : customer.Name
vs
(customer == null) ? string.empty : customer.Name
我个人认为后者不那么模棱两可,也更容易阅读。
正如其他人指出的那样,实际的差异可以忽略不计。
虽然差别非常非常小,但差别仍然存在。
""在String时创建一个对象。空则不然。但是这个对象只创建一次,如果代码中有另一个"",就会从字符串池中引用它。 String和String是一样的,但是我建议使用String。空(以及字符串。格式字符串。因为点表示法表示的是类,而不是操作符,而且类以大写字母开头符合c#编码标准。
这完全是一个代码风格的偏好,就像。net如何处理字符串一样。然而,以下是我的观点:
我总是使用BCL类型名称访问静态方法,属性和字段:字符串。Empty或Int32.TryParse(…)或Double。ε
我总是在声明新实例时使用c#关键字:或者string foo = "bar";
我很少使用未声明的字符串字面量,因为我喜欢能够扫描代码,将它们组合成可重用的命名常量。编译器无论如何都会用字面量替换常量,所以这是一种避免神奇的字符串/数字,并通过名称赋予它们更多含义的方法。另外,更改值更容易。
The empty string is like empty set just a name that everybody uses to call "". Also in formal languages strings created from an alphabet that have zero length are called the empty string. Both set and string have a special symbol for it. Empty string: ε and empty set: ∅. If you want to talk about this zero length string you will call it the empty string so everybody knows exactly what you are referring to. Now in case you name it the empty string why not use string.Empty in code, its shows the intention is explicit. Downside is that it’s not a constant and therefore not available everywhere, like in attributes. (It's not a constant for some technical reasons, see the reference source.)
我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个using System;在你的档案里。
至于在字符串上选择“”。空,这是个人喜好,应该由你的团队决定。