gpt4 book ai didi

c# - 为什么在三元运算符中分配 null 失败 : no implicit conversion between null and int?

转载 作者:可可西里 更新时间:2023-11-01 08:33:44 25 4
gpt4 key购买 nike

此操作失败并显示 'null' 和 'int' 之间没有隐式转换

long? myVar = Int64.Parse( myOtherVar) == 0 ? null : Int64.Parse( myOtherVar);

然而,这成功了:

if( Int64.Parse( myOtherVar) == 0)
myVar = null;
else
myVar = Int64.Parse( myOtherVar);

有没有办法让三元运算符成功?

最佳答案

编译器在确定右侧的类型时会忽略左侧。所以当它试图推断出的类型时

Int64.Parse(myOtherVar) == 0 ? null : Int64.Parse(myOtherVar)

这样做并没有注意到左侧是一个 long? 这一事实。为了确定右侧的类型,它注意到

Int64.Parse(myOtherVar)

是一个 long,现在尝试查看 null 是否或可以隐式转换为 long。由于它不能,您会看到您看到的错误消息。

来自 C# 规范的 §7.14:

A conditional expression of the form b ? x : y....

The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

(1) If x has type X and y has type Y then

a. If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

b. If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

c. Otherwise, no expression type can be determined, and a compile-time error occurs.

(2) If only one of x and y has a type, and both x and y, of areimplicitly convertible to that type, then that is the type of the conditional expression.

(3) Otherwise, no expression type can be determined, and a compile-time error occurs.

请注意,我们处于情况 (2) 中,其中 xnull 并且没有类型并且 yInt64 .Parse(myOtherVar) 并且类型为 long。请注意,x 不能隐式转换为 y 的类型。因此,(1) 和 (2) 都在上面失败,我们导致 (3),这会导致引发您的问题的编译时错误。 请注意上面的隐含结论,即左侧在确定右侧的类型方面不起作用。

要纠正这个替换

Int64.Parse(myOtherVar)

(long?)Int64.Parse(myOtherVar)

现在,原因

myVar = null;

可以将 myVar 声明为 long? 是因为编译器知道存在从 nulllong 的隐式转换?

最后,如果 myOtherVar 无法解析为 longInt64.Parse 将抛出异常。请注意,您还执行了两次解析,这是不必要的。更好的模式是

long value;
if(Int64.TryParse(myOtherVar, out value)) {
myVar = value == 0 ? null : (long?)value;
}
else {
// handle case where myOtherVar couldn't be parsed
}

关于c# - 为什么在三元运算符中分配 null 失败 : no implicit conversion between null and int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4290203/

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