为什么我的“if”的速记版本不能使用不同的实现进行编译

本文关键字:实现 编译 版本 if 我的 为什么 不能 | 更新日期: 2023-09-27 18:37:26

我有以下接口:

interface IMyInterface {}

以及以下两个实现:

class MyImplementation : IMyInterface {}
class MyOtherImplementation : IMyInterface {}

鉴于此,以下编译:

IMyInterface ReturnImplementation()
{
   if(condition)
   {
      return new MyImplementation();
   }
   else
   {
      return new MyOtherImplementation();
   }
}

但这不会:

IMyInterface ReturnImplementation()
{
   return condition ? new MyImplementation() : new MyOtherImplementation();
}

问题

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

为什么我的“if”的速记版本不能使用不同的实现进行编译

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

您没有阅读规范:)

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

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

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

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

此时,编译器会注意到存在从 MyOtherImplementationIMyInterface 的隐式转换,但反之则不然,并选择IMyInterface作为运算符的整体类型。