gpt4 book ai didi

c# - 三元(条件)运算符与返回 Action 的 if 语句之间的区别

转载 作者:行者123 更新时间:2023-11-30 13:57:38 25 4
gpt4 key购买 nike

考虑以下无法编译的代码:

class WhyNot
{
private Action _doSomething;
public bool ThisOrThat;

public WhyNot()
{
_doSomething = ThisOrThat ? DoThis : DoThat;
}
private void DoThis()
{}
private void DoThat()
{}
}

我知道这行不通,因为 methods dont intrisically have a type ,而代表这样做,所以 explicit cast must be made .

_doSomething = ThisOrThat ? (Action)DoThis : (Action)DoThat;    

我不理解的是,为什么标准 if 语句会在三元运算符失败的情况下成功转换它们?

if (ThisOrThat)
_doSomething = DoThis;
else
_doSomething = DoThat;

为什么运算符之间存在差异?

最佳答案

Why explicit cast is required in Conditional operator

_doSomething = ThisOrThat ?  DoThis : DoThat; 

来自 this answer来自 Jon Skeet:

as the expression. What's the type of that? What delegate type should the method groups be converted to? The compiler has no way of knowing. If you cast one of the operands, the compiler can check that the other can be converted though

针对您的问题:

Why it is allowed in if statement

您正在执行一个简单的分配,其中左侧是 Action,右侧是一个方法组。存在隐式转换

参见 Assignment Operator(=) C#

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result. The operands must be of the same type (or the right-hand operand must be implicitly convertible to the type of the left-hand operand)

关于c# - 三元(条件)运算符与返回 Action 的 if 语句之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337142/

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