为什么我的'if'的速记版本不会用不同的实现编译?

0 .net c# types if-statement interface

我有以下界面:

interface IMyInterface {}
Run Code Online (Sandbox Code Playgroud)

以下两个实现:

class MyImplementation : IMyInterface {}

class MyOtherImplementation : IMyInterface {}
Run Code Online (Sandbox Code Playgroud)

鉴于此,以下编译:

IMyInterface ReturnImplementation()
{
   if(condition)
   {
      return new MyImplementation();
   }
   else
   {
      return new MyOtherImplementation();
   }
}
Run Code Online (Sandbox Code Playgroud)

但是,并不:

IMyInterface ReturnImplementation()
{
   return condition ? new MyImplementation() : new MyOtherImplementation();
}
Run Code Online (Sandbox Code Playgroud)

为什么?假设它应该编译,我误解了什么?它是否简单,因为速记if指定了从中选择完全相同的类型?如果是这样,为什么?为什么这样受限制?

Jon*_*eet 12

假设它应该编译,我误解了什么?

你没有阅读规范:)

基本上,条件运算符要求任一所述的第二和第三运算数是相同类型的,或者是有一个从它们中的一个到另一个(而不是其他方式轮)的隐式转换.换句话说,运算符的整体结果类型必须是第二个操作数的类型或第三个操作数的类型.

这是编译器给大家介绍的隐式转换错误消息的原因-你要求它试图隐式转换或者MyImplementationMyOtherImplementation反之亦然.

在您的情况下,您希望结果类型为IMyInterface- 所以您应该将其中一个操作数(其中一个)转换为该类型:

return condition ? (IMyInterface) new MyImplementation() : new MyOtherImplementation();
Run Code Online (Sandbox Code Playgroud)

此时,编译器将注意到隐式转换MyOtherImplementation,IMyInterface但反之亦然,并选择IMyInterface运算符的整体类型.