c# - 为什么字符串类型的默认值是null而不是空字符串?

标签 c# string default-value

null 测试我所有的字符串非常烦人在我可以安全地应用类似 ToUpper() 的方法之前, StartWith()等等……

如果默认值为string是空字符串,我不必测试,我觉得它与其他值类型更一致,如 intdouble例如。 另外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/

相关文章:

c++ - 非静态成员作为 C++ 中的默认参数

php - <select> 下拉默认值

数字类型的 C++ 非零默认值 - 重新发明?

c# - AutoMapper 与 ValueInjecter

python - 查找字符串中所有可能的子字符串。 Python 正则表达式

php - 替换重音字符php

r - 从 R 中的文本文件中提取模式子字符串

c# - NUnit 未运行套件测试

c# - 未满18岁如何不注册

c# - string.Format() 参数