关于c#:为什么我的’if’的简写版本不能使用不同的实现进行编译?

本问题已经有最佳答案,请猛点这里访问。

我有以下界面:

1
interface IMyInterface {}

以及以下两个实现:

1
2
3
class MyImplementation : IMyInterface {}

class MyOtherImplementation : IMyInterface {}

鉴于此,将编译以下内容:

1
2
3
4
5
6
7
8
9
10
11
IMyInterface ReturnImplementation()
{
   if(condition)
   {
      return new MyImplementation();
   }
   else
   {
      return new MyOtherImplementation();
   }
}

但这不是:

1
2
3
4
IMyInterface ReturnImplementation()
{
   return condition ? new MyImplementation() : new MyOtherImplementation();
}

问题

为什么?我在假定应该编译时会误解什么?就像速记if指定完全相同的类型一样简单吗?如果是这样,为什么?为什么以这种方式进行限制?


What am I misunderstanding in assuming that it should compile?

您没有阅读规格:)

基本上,条件运算符要求第二个操作数和第三个操作数具有相同的类型,或者从其中一个操作数到另一个操作数进行隐式转换(而不是相反)。换句话说,运算符的总结果类型必须是第二个操作数的类型或第三个操作数的类型。

这就是编译器向您提供有关隐式转换的错误消息的原因-您正在要求编译器尝试将MyImplementation隐式转换为MyOtherImplementation,反之亦然。

在您的情况下,您希望结果类型为IMyInterface-因此您应将其中一个操作数(其中一个或两个)强制转换为该类型:

1
return condition ? (IMyInterface) new MyImplementation() : new MyOtherImplementation();

到那时,编译器将注意到从MyOtherImplementationIMyInterface的隐式转换,但反之则没有,请选择IMyInterface作为运算符的整体类型。