gpt4 book ai didi

c# - 分配 bool 值? bool

转载 作者:行者123 更新时间:2023-11-30 22:11:43 29 4
gpt4 key购买 nike

考虑以下代码:

bool x;
bool? y = null;
x = y?? true;

bool? 分配给 bool 是一个编译时错误,但上面的代码在编译和运行时都成功了。为什么?尽管第三条语句确保我们永远不会将 null 分配给 x,但如果 y 不为 null,我们仍然会分配一个 bool ?bool,所以它应该是编译器 POV 的错误,不是吗?

还是 C# 编译器足够聪明,可以发现一段特定的代码不可能创建将 null 分配给 x 的情况?

最佳答案

这个表达式的类型:

y ?? true

bool,不是bool?

来自 C# 5 规范的第 7.13 节:

The type of the expression a ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a (provided that a has a type), B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type, or A otherwise. Specifically, a ?? b is processed as follows:

  • If A exists and is not a nullable type or a reference type, a compile-time error occurs.
  • If b is a dynamic expression, the result type is dynamic. At run-time, a is first evaluated. If a is not null, a is converted to dynamic, and this becomes the result. Otherwise, b is evaluated, and this becomes the result.
  • Otherwise, if A exists and is a nullable type and an implicit conversion exists from b to A0, the result type is A0. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0, and this becomes the result. Otherwise, b is evaluated and converted to type A0, and this becomes the result.
  • Otherwise, if A exists and an implicit conversion exists from b to A, the result type is A. At run-time, a is first evaluated. If a is not null, a becomes the result. Otherwise, b is evaluated and converted to type A, and this becomes the result.
  • Otherwise, if b has a type B and an implicit conversion exists from a to B, the result type is B. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 (if A exists and is nullable) and converted to type B, and this becomes the result. Otherwise, b is evaluated and becomes the result.
  • Otherwise, a and b are incompatible, and a compile-time error occurs.

对于您的情况,我们在第三个项目符号中:

  • A 是 bool?
  • A0bool
  • B 是bool

...所以结果类型是 bool,您可以将其分配给 bool 类型的变量。

关于c# - 分配 bool 值? bool ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20087428/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com