可能重复:
条件运算符无法隐式转换?
为什么null需要显式类型转换?
我有一个搜索,并没有找到一个很好的解释为什么发生以下情况.
我有两个具有共同接口的类,我尝试使用三元运算符初始化此接口类型的实例,如下所示但是无法编译错误"无法确定条件表达式的类型,因为之间没有隐式转换'xxx.Class1'和'xxx.Class2':
public ConsoleLogger : ILogger { .... }
public SuppressLogger : ILogger { .... }
static void Main(string[] args)
{
.....
// The following creates the compile error
ILogger logger = suppressLogging ? new SuppressLogger() : new ConsoleLogger();
}
Run Code Online (Sandbox Code Playgroud)
如果我明确地将第一个conditioin强制转换为我的界面,这是有效的:
ILogger logger = suppressLogging ? ((ILogger)new SuppressLogger()) : new ConsoleLogger();
Run Code Online (Sandbox Code Playgroud)
显然我总能做到这一点:
ILogger logger;
if (suppressLogging)
{
logger = new SuppressLogger();
}
else
{
logger = new ConsoleLogger();
}
Run Code Online (Sandbox Code Playgroud)
替代方案很好,但我不能完全理解为什么第一个选项因隐式转换错误而失败,因为在我看来,这两个类都是ILogger类型,我不是真的想要进行转换(隐式或显式) ).我敢肯定这可能是一个静态语言编译问题,但我想了解发生了什么.