c# - 为什么 "null"出现在 C# 和 Java 中?

标签 c# java null

我们注意到我们用 C#(或 Java)开发的软件中的许多错误会导致 NullReferenceException。

语言中甚至包含“null”有什么原因吗?

毕竟,如果没有“null”,我就没有bug了,对吧?

换句话说,语言中的哪些功能没有 null 就不能工作?

最佳答案

Anders Hejlsberg,“C# 之父”,刚刚在 his Computerworld interview 中谈到了这一点:

For example, in the type system we do not have separation between value and reference types and nullability of types. This may sound a little wonky or a little technical, but in C# reference types can be null, such as strings, but value types cannot be null. It sure would be nice to have had non-nullable reference types, so you could declare that ‘this string can never be null, and I want you compiler to check that I can never hit a null pointer here’.

50% of the bugs that people run into today, coding with C# in our platform, and the same is true of Java for that matter, are probably null reference exceptions. If we had had a stronger type system that would allow you to say that ‘this parameter may never be null, and you compiler please check that at every call, by doing static analysis of the code’. Then we could have stamped out classes of bugs.

Cy 团队的前软件设计工程师(现在在 Google 工作)Cyrus Najmabadi 在他的博客上讨论了这个主题:(1st2nd3rd4th)。 似乎采用不可为空类型的最大障碍是符号会扰乱程序员的习惯和代码库。大约 70% 的 C# 程序引用最终可能是不可为空的。

如果你真的想在 C# 中使用不可为空的引用类型,你应该尝试使用 Spec# 这是一个允许使用“!”的 C# 扩展作为一个不可为空的符号。

static string AcceptNotNullObject(object! s)
{
    return s.ToString();
}

关于c# - 为什么 "null"出现在 C# 和 Java 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/178026/

相关文章:

c# - 显示从数据库到 WPF 应用程序的多行

c# - 删除 HTTP 服务器和 X-Powered-By header

java - 在实体对象中将 native SQL 与默认 Hibernate 行为混合?

java - 如何从一台计算机访问同一网络上的另一台计算机的本地主机服务器

python - 在Python中将CSV空白单元格转换为SQL NULL

c# - 异常 "Collection has been modified",当它还没有

java - 无法使用 Vert.x 通过 TLS 连接到主机

c++ - 传递 "No/Null/0"作为引用?

function - 对于获取对象但可能找不到它的函数,最好的 func 签名是什么?

C# 子串 : Removing first three characters