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`禁止?
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
