为什么条件运算符 (?:
) 在与从单个基类型继承的两个类型一起使用时不起作用?
我的例子是:
ActionResult foo = (someCondition)?
RedirectToAction("Foo","Bar") :
Redirect(someUrl);
长格式工作正常的地方:
ActionResult foo;
if(someCondition)
{
foo = RedirectToAction("Foo","Bar");
}
else
{
foo = Redirect(someUrl);
}
RedirectToRouteResult
和 RedirectResult
这两个返回类型都继承自 ActionResult
。
最佳答案
How come the conditional operator (?:) doesn't work when used with two types that inherit from a single base type?
根据语言规范,条件表达式的类型必须是第二个操作数的类型或第三个操作数的类型。编译器不会试图找到一个共同的基类型,或者两个操作数都可以转换成的另一种类型。表达式的使用不会影响其类型的确定方式 - 因此变量赋值在这里无关紧要。
至于为什么语言是这样定义的——它使得指定、实现、测试和预测变得相当简单。这在语言设计中相当普遍 - 从长远来看,保持语言简单通常是更好的选择,即使它在某些特定情况下会稍微有点尴尬。
有关详细信息,请参阅 C# 4 规范的第 7.14 节。
将第二个或第三个操作数转换为您实际上想要的条件表达式类型是解决问题的方法。请注意,这种情况经常出现的另一种情况是可空类型:
// Invalid
int? a = SomeCondition ? null : 10;
// All valid
int? a = SomeCondition ? (int?) null : 10;
int? b = SomeCondition ? default(int?) : 10;
int? c = SomeCondition ? null : (int?) 10;
关于c# - 条件运算符不适用于继承相同基类型的两种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10964065/