本文介绍了三元运算符语法以选择接口的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这段代码无法编译:

I am wondering why this line of code doesn't compile:

ILogStuff Logger = (_logMode) ? new LogToDisc() : new LogToConsole();

请注意,两个类 LogToDisc LogToConsole 实现 ILogStuff ,而 _logMode 是布尔变量。我得到的错误消息是:

Note that both classes LogToDiscand LogToConsole implement ILogStuff, and _logMode is a boolean variable. The error message I get is:

但是为什么要有一个呢?我想念什么?

But why should there be one? What am I missing?

推荐答案

三元运算符没有隐式转换。您需要通过三元运算符将返回的对象强制转换为 ILogStuff ,这在Eric Lippert的答案

There is not implicit conversion available for ternary operator. You need to cast the returned object by ternary operator to ILogStuff, This is very well explain in Eric Lippert's answer for the question Implicit conversion issue in a ternary condition

ILogStuff Logger = (_logMode) ? (ILogStuff) new LogToDisc() : (ILogStuff) new LogToConsole();

摘自《 C#语言规范》第7.13章:


  • 如果X和Y是相同类型,则这是条件表达式的类型。

  • 否则,如果存在从X到Y的隐式转换(第6.1节),但不存在从Y到X的隐式转换,则Y是条件表达式的类型。

  • 否则,如果存在从Y到X的隐式转换(第6.1节),但是从X到Y不存在,则X是条件表达式的类型。

  • 否则,无法确定表达式类型,并且会发生编译时错误。

  • If X and Y are the same type, then this is the type of the conditional expression.
  • Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
  • Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
  • Otherwise, no expression type can be determined, and a compile-time error occurs.

这篇关于三元运算符语法以选择接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 00:48