gpt4 book ai didi

c# - Null-Coalescing 运算符结果的隐式转换

转载 作者:太空狗 更新时间:2023-10-29 21:18:59 25 4
gpt4 key购买 nike

有了以下对 C# 中空合并运算符 (??) 的理解。

int? input = -10;
int result = input ?? 10;//Case - I
//is same as:
int result = input == null? input : 10; // Case - II

虽然根据定义和用法,案例 I 和案例 II 是相同的。

令人惊讶的是,在 Case-I 中,编译器能够隐式转换 int?到 int 而在 Case-II 中它显示错误:'Error 1 Cannot implicitly convert type 'int?'到 'int'"

关于空合并运算符,我遗漏了什么?

感谢您的关注。

最佳答案

要使第二种情况与三元运算符一起使用,您可以使用以下内容:

int result = input != null ? input.Value : 10;

Value Nullable<T> 的属性(property)类型返回 T值(在本例中为 int )。

另一种选择是使用 Nullable<T>.HasValue :

int result = input.HasValue ? input.Value : 10;

myNullableInt != null construct 只是上述 HasValue 的语法糖打电话。

关于c# - Null-Coalescing 运算符结果的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8898223/

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