为什么"零"在C#和Java present? [英] Why is "null" present in C# and Java?

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

问题描述

我们注意到,很多在我们的软件缺陷在C#(或Java)开发导致一个NullReferenceException。

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

有没有为什么空甚至被列入语言理由吗?

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

毕竟,如果没有空,我就没有错误了吧?

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

在换句话说,有什么特点的语言不能没有空工作?

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

推荐答案

安德斯Hejlsberg为C#之父,只是谈到这点的他的计算机世界采访

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

例如,在类型系统我们没有值和引用类型和类型为空性之间的分隔。这听起来可能有点靠不住还是有点技术,但在C#中引用类型可以为空,如字符串,但是值类型不能为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’.

这是人们碰到的今天,在我们的平台上用C#编码,同样是Java的真正对于这个问题的错误的50%,很可能是空引用异常。如果我们有一个更强的类型系统,该系统将允许你说,'这个参数可能永远是空的,你编译请检查在每一个电话,通过执行code的静态分析。然后,我们可以消灭了阶级的bug。

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.

赛勒斯Najmabadi,在C#队(现在在谷歌工作)前任软件设计工程师讨论:(的1st 2日 3 ,的 4 )。
看来,要通过非可空类型的最大障碍就是符号会扰乱程序员习惯和code基地。像C#程序引用的70%的东西很可能最终达到为不可为空的。

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#非空的引用类型,你应该尝试使用规格#
这是一个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 present?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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