有条件的经营者不与两种类型的继承相同的基本类型工作 [英] Conditional operator doesn't work with two types that inherit the same base type

查看:119
本文介绍了有条件的经营者不与两种类型的继承相同的基本类型工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么条件运算符()两种类型,从一个基本类型继承使用时无法正常工作

我的例子是:

 的ActionResult富=(someCondition)?
                      RedirectToAction(富,酒吧):
                      重定向(someUrl);

如果长期形成正常工作:

 的ActionResult富;如果(someCondition)
{
  富= RedirectToAction(富,酒吧);
}
其他
{
  富=重定向(someUrl);
}

都返回类型, RedirectToRouteResult RedirectResult ,从的ActionResult


解决方案

  

为什么条件运算符(?:)有两种类型,从一个基本类型继承使用时不起作用?


的类型的条件前pression的必须的或者的所述第二操作数的类型的的第三操作数的类型,按照语言规范。编译器不试图找到一个共同的基础类型或另一种类型的两个操作数可以被转换为。在使用ex pression的的并不影响它的类型是如何确定 - 这样的变量赋值在这里无关紧要

至于为什么的语言定义是这样的 - 它使相当简单指定,实施,测试和predict。这是语言设计相当普遍 - 保持语言简洁通常是一个更好的选择,从长远来看,即使这使得它稍微在某些特定的情况下尴尬

查看C#4规范的7.14节的更多细节。

铸造第二个或第三个操作数,你的的类型实际上的想为条件前pression是解决问题的方式。需要注意的是另一种情况这往往在出现是可空类型:

  //无效
诠释? A = SomeCondition?空:10;//所有有效
诠释? A = SomeCondition? (INT?)空:10;
诠释? B = SomeCondition?默认情况下(INT):10;
诠释? C = SomeCondition?空:(INT?)10;

How come the conditional operator (?:) doesn't work when used with two types that inherit from a single base type?

The example I have is:

ActionResult foo = (someCondition)? 
                      RedirectToAction("Foo","Bar") :
                      Redirect(someUrl);

Where the long form works fine:

ActionResult foo;

if(someCondition)
{
  foo = RedirectToAction("Foo","Bar");
}
else
{
  foo = Redirect(someUrl);
}

Both return types, RedirectToRouteResult and RedirectResult, inherit from ActionResult.

解决方案

How come the conditional operator (?:) doesn't work when used with two types that inherit from a single base type?

The type of the conditional expression has to be either the type of the second operand or the type of the third operand, as per the language specification. The compiler doesn't try to find a common base type, or another type that both operands can be converted to. The use of the expression doesn't affect how its type is determined - so the variable assignment is irrelevant here.

As for why the language is defined like this - it makes it considerably simpler to specify, implement, test and predict. This is fairly common in language design - keeping the language simple is usually a better bet in the long run, even if it makes it slightly more awkward in some specific situations.

See section 7.14 of the C# 4 spec for more details.

Casting either the second or third operand to the type that you actually want for the conditional expression is the way to fix the problem. Note that another situation this often comes up in is nullable types:

// 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;

这篇关于有条件的经营者不与两种类型的继承相同的基本类型工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆