我们注意到我们用 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 在他的博客上讨论了这个主题:(1st、2nd、3rd、4th)。 似乎采用不可为空类型的最大障碍是符号会扰乱程序员的习惯和代码库。大约 70% 的 C# 程序引用最终可能是不可为空的。
如果你真的想在 C# 中使用不可为空的引用类型,你应该尝试使用 Spec# 这是一个允许使用“!”的 C# 扩展作为一个不可为空的符号。
static string AcceptNotNullObject(object! s)
{
return s.ToString();
}
关于c# - 为什么 "null"出现在 C# 和 Java 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/178026/