为 null
测试我所有的字符串非常烦人在我可以安全地应用类似 ToUpper()
的方法之前, StartWith()
等等……
如果默认值为string
是空字符串,我不必测试,我觉得它与其他值类型更一致,如 int
或 double
例如。
另外Nullable<String>
有道理。
那么为什么C#的设计者选择使用null
作为字符串的默认值?
注:这与this question有关,但更侧重于为什么而不是如何处理它。
最佳答案
Why is the default value of the string type null instead of an empty string?
因为 string
是一个引用类型,所有引用类型的默认值为null
.
It's quite annoying to test all my strings for null before I can safely apply methods like ToUpper(), StartWith() etc...
这与引用类型的行为一致。在调用它们的实例成员之前,应该检查是否存在空引用。
If the default value of string were the empty string, I would not have to test, and I would feel it to be more consistent with the other value types like int or double for example.
将默认值分配给除 null
以外的特定引用类型会使它不一致。
Additionally
Nullable<String>
would make sense.
Nullable<T>
使用值类型。值得注意的是 Nullable
原文没有介绍.NET platform所以如果他们改变了那个规则,就会有很多损坏的代码。(礼貌 @jcolebrand )
关于c# - 为什么字符串类型的默认值是null而不是空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14337551/