Nullable types and the ternary operator: why is `? 10 : null` forbidden?(可空类型和三元运算符:为什么是`?10:null`禁止?)
问题描述
我刚刚遇到了一个奇怪的错误:
I just came across a weird error:
private bool GetBoolValue()
{
//Do some logic and return true or false
}
然后,在另一种方法中,像这样:
Then, in another method, something like this:
int? x = GetBoolValue() ? 10 : null;
简单,如果方法返回true,则将10赋给Nullableint x.否则,将 null 分配给 nullable int.但是,编译器抱怨:
Simple, if the method returns true, assign 10 to the Nullableint x. Otherwise, assign null to the nullable int. However, the compiler complains:
错误 1 无法确定条件表达式的类型,因为 int 和 <null> 之间没有隐式转换.
Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between
intand<null>.
我要疯了吗?
推荐答案
编译器首先尝试计算右手表达式:
The compiler first tries to evaluate the right-hand expression:
GetBoolValue() ? 10 : null
10 是 int 文字(不是 int?),而 null 是,嗯,空.这两者之间没有隐式转换,因此出现错误消息.
The 10 is an int literal (not int?) and null is, well, null. There's no implicit conversion between those two hence the error message.
如果您将右侧表达式更改为以下之一,则它会编译,因为在 int? 和 null (#1) 之间以及在int 和 int? (#2, #3).
If you change the right-hand expression to one of the following then it compiles because there is an implicit conversion between int? and null (#1) and between int and int? (#2, #3).
GetBoolValue() ? (int?)10 : null // #1
GetBoolValue() ? 10 : (int?)null // #2
GetBoolValue() ? 10 : default(int?) // #3
这篇关于可空类型和三元运算符:为什么是`?10:null`禁止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可空类型和三元运算符:为什么是`?10:null`禁止?
基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
