C# 不能设置int?是否在?:运算符中为空
有时我可以将C# 不能设置int?是否在?:运算符中为空,c#,C#,有时我可以将null赋值给int?,但不能在中赋值:,为什么 范例 int? a; // good int? b; // good a = null; // why is this allowed? b = (a != null) ? 1 : null /* and this not allowed? */; b = (a != null) ? 1 : (int?)null /* this is a fix */; 发件人: 第一个_表达式和第二个
null
赋值给int?
,但不能在中赋值:代码>,为什么
范例
int? a; // good
int? b; // good
a = null; // why is this allowed?
b = (a != null) ? 1 : null /* and this not allowed? */;
b = (a != null) ? 1 : (int?)null /* this is a fix */;
发件人:
第一个_表达式和第二个_表达式的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换
其他的
那么,在b=(a!=null)中?1:null
第一个参数的类型是int
,第二个参数是null
,这违反了上述规则
在第二种情况下,int
可以隐式转换为(int?)null
,这就是它工作的原因。因为?:运算符中的两个表达式应该具有相同的类型,或者应该存在从一个到另一个的隐式转换。int(1)和null的情况并非如此。另外,一旦您将null
转换为(int?)null
,现在就存在一个隐式转换。