c# - 我怎么能在int上执行方法?在没有 NullReferenceException 的情况下设置为 null?

标签 c# nullable

我在 MSDN 上读到:

The null keyword is a literal that represents a null reference, one that does not refer to any object.

但是我看到下面的代码运行时没有抛出任何异常:

int? i = null;
var s = i.ToString();

那么如果变量i 为null,为什么我可以执行它的方法呢?

最佳答案

因为 int?实际上是一个 Nullable<Int32> Nullable<T> struct , 和一个结构 cannot be null .

就是这样Nullable types work.它们不是引用值,所以它们不能为空,但当它们被认为等同于空时,它们可以有一个状态。

您可以获得有关Nullable<T> 的更多详细信息在 how are nullable types implemented under the hood in .net? 中实现和 Nullable<T> implementation


虽然正如@JeppeStigNielsen 所指出的,但在一种情况下您可以获得 NRE:

However: When boxed to a reference type, special treatment of Nullable<> ensures we do get a true null reference. So for example i.GetType() with i as in the question will blow up with the NullReferenceException. That is because this method is defined on object and not overridable

关于c# - 我怎么能在int上执行方法?在没有 NullReferenceException 的情况下设置为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41837684/

相关文章:

sql server批量插入空值到时间列

c# - 具有 Type<T> 可为空值的 <T> 类型的类

c# - ASP.NET MVC 路由不适用于 .html 扩展

c# - 使用 Web 服务时出错 : An existing connection was forcibly closed

c# - Swashbuckle xml 注释中带有&符号的查询字符串

c# - 如何在 Excel 操作 Pane 中使用 WPF 控件?

java - @NotNull 和@Nullable,与java 注解相矛盾

java - fragment 问题中的 NullPointerException

c# - 使用 newtonsoft json.net 反序列化字符串时,如何将空字符串转换为 null 以获得可为 null 的 int?

C# xml : How to save nested rows