为什么是“空"?存在于 C# 和 Java 中? [英] Why is "null" present in C# and Java?

查看:22
本文介绍了为什么是“空"?存在于 C# 和 Java 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.

语言中甚至包含null"是否有原因?

Is there a reason why "null" has even been included in the language?

毕竟,如果没有null",我就没有错误,对吧?

After all, if there were no "null", I would have no bug, right?

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

In other words, what feature in the language couldn't work without null?

推荐答案

Anders Hejlsberg,C# 之父",刚刚在 他对计算机世界的采访:

Anders Hejlsberg, "C# father", just spoke about that point in his Computerworld interview:

例如,在类型系统中,我们没有将值类型和引用类型以及类型的可空性分开.这听起来可能有点古怪或有点技术性,但在 C# 中,引用类型可以为 null,例如字符串,但值类型不能为 null.拥有不可为空的引用类型肯定会很好,因此您可以声明此字符串永远不能为空,我希望您的编译器检查我永远不会在这里命中空指针".

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% 的错误,在我们的平台上使用 C# 编码,Java 也是如此,可能是空引用异常.如果我们有一个更强大的类型系统,它允许你说这个参数可能永远不会为空,并且你的编译器请在每次调用时检查它,通过对代码进行静态分析".然后我们就可以消除各种错误.

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.

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

Cyrus Najmabadi, a former software design engineer on the C# team (now working at Google) discuss on that subject on his blog: (1st, 2nd, 3rd, 4th). It seems that the biggest hindrance to the adoption of non-nullable types is that notation would disturb programmers’ habits and code base. Something like 70% of references of C# programs are likely to end-up as non-nullable ones.

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

If you really want to have non-nullable reference type in C# you should try to use Spec# which is a C# extension that allow the use of "!" as a non-nullable sign.

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

这篇关于为什么是“空"?存在于 C# 和 Java 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆