无法将null分配给隐式类型的变量 [英] Cannot assign null to an implicitly-typed variable
问题描述
根据Visual Studio,这不行:
According to Visual Studio this is not ok:
var foo = null;
但这没关系:
var foo = false ? (double?)null : null;
为什么?(double?)null
是否还会影响else分支中的 null
?
Why? Is the (double?)null
affecting also the null
in the else branch?
推荐答案
隐式键入变量声明/赋值有两个目的:
Implicitly typed variable declaration/assignment serves two purposes:
- 确定变量的值,并且
- 确定变量的类型.
您的第一个声明的值带有 null
,没有办法弄清楚类型(它可以是从 System.Object
派生的任何内容,也可以是Nullable< T>
).这就是为什么这是一个错误.
Your first declaration has null
for the value, with no way to figure out the type (it could be anything derived from System.Object
, or a Nullable<T>
). That is why it is an error.
您的第二个声明由于强制类型转换而将类型精确定位为 Nullable< double>
.这就是C#允许的原因.
Your second declaration pinpoints the type as Nullable<double>
because of the cast. That is why C# allows it.
不用说 double吗?foo = null
会更容易阅读.
这篇关于无法将null分配给隐式类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!