为什么不递增可空< INT>抛出一个异常? [英] Why doesn't incrementing Nullable<int> throw an exception?

查看:143
本文介绍了为什么不递增可空< INT>抛出一个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请你解释一下,为什么Console.WriteLine写空行( Console.WriteLine(空)给我的编译错误),为什么没有的NullReferenceException(连 A + = 1 不应该提高它)?

 诠释?一个=无效; 
A ++; //为什么没有的NullReferenceException?
Console.WriteLine(一); //空行


解决方案

您所观察的效果。一个的提升运算符



从C#5规范的第7.3.7:



< BLOCKQUOTE>

抬升经营许可证预定义的,也可以用这些类型的空形式使用的非空值类型进行操作的用户定义运算。解除运营商正在从满足某些要求的预定义和用户定义的运营商构建的,如下面的描述:




  • 对于一元运算符 + ++ - - ! 〜
    如果操作数和结果类型都为非空值类型运算符的提升形式存在。该提升形式是通过将一个修改操作数和结果类型构造。提升运算,如果操作数为null产生一个空值。否则,提升运算解开操作数,应用基础运算符,并包装结果。




所以基本上, A ++ 在这种情况下是的结果的表达式(作为诠释?)和变量保持不变。



当你调用

  Console.WriteLine(一); 

这就是被包装成对象,它转换它为空引用,这是打印为一个空行。


Could you please explain, why does Console.WriteLine write empty line (Console.WriteLine(null) give me compilation error) and why there isn't NullReferenceException (even a+=1 shouldn't raise it)?

int? a = null;
a++; // Why there is not NullReferenceException? 
Console.WriteLine(a); // Empty line

解决方案

You're observing the effects of a lifted operator.

From section 7.3.7 of the C# 5 specification:

Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types. Lifted operators are constructed from predefined and user-defined operators that meet certain requirements, as described in the following:

  • For the unary operators + ++ - -- ! ~ a lifted form of an operator exists if the operand and result types are both non-nullable value types. The lifted form is constructed by adding a single ? modifier to the operand and result types. The lifted operator produces a null value if the operand is null. Otherwise, the lifted operator unwraps the operand, applies the underlying operator, and wraps the result.

So basically, a++ in this case is an expression with a result of null (as an int?) and the variable is left untouched.

When you call

Console.WriteLine(a);

that's being boxed into object, which converts it to a null reference, which is printed as an empty line.

这篇关于为什么不递增可空&LT; INT&GT;抛出一个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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