【发布时间】:2013-12-18 16:23:52
【问题描述】:
考虑以下无法编译的代码:
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;
为什么运营商之间有区别?
【问题讨论】:
-
您确定 _doSomething 在 if 语句的情况下具有值吗?也许它是空的?
-
_doSomething = ThisOrThat ? (Action) DoThis : DoThat;这也可以编译。你可能会看到this answer from Jon Skeet -
@Habib 我在帖子中引用了那个答案,(必须进行明确的演员表)你可以做一侧或另一侧。只是不知道为什么 IF 能做到。
-
@paqogomez:我认为答案在 Jon 的回答中——"[The compiler] 没有使用您试图分配给变量的事实来计算条件表达式的类型"
-
请注意,
var foo = MethodName;的分配有类似的问题 - 它无法确定var的类型。
标签: c# if-statement ternary-operator