gin*_*boy 1 c# interface .net-3.5 inline-if
public class Foo : IFooBarable {...}
public class Bar : IFooBarable {...}
Run Code Online (Sandbox Code Playgroud)
那么为什么这不会编译......
int a = 1;
IFooBarable ting = a == 1 ? new Foo() : new Bar();
Run Code Online (Sandbox Code Playgroud)
但这会......
IFooBarable ting = a == 1 ? new Foo() : new Foo();
IFooBarable ting = a == 1 ? new Bar() : new Bar();
Run Code Online (Sandbox Code Playgroud)
编译器首先尝试评估右手表达式:
? new Foo() : new Bar();
Run Code Online (Sandbox Code Playgroud)
这两者之间没有隐式转换因此错误消息.你可以这样做:
IFooBarable ting = a == 1 ? (IFooBarable)(new Foo()) : (IFooBarable)(new Bar());
Run Code Online (Sandbox Code Playgroud)
这将在C#语言规范的第7.13节中介绍.基本上杀死这种情况的是,三元操作数的2个值的类型之间必须存在隐式转换.这种转换被认为是变量类型的绝对值.
所以要么Foo必须是可转换的,Bar反之亦然.也不会发生编译错误.
后者2可以工作,因为他们只考虑1种类型(Foo或者Bar).因为它们属于同一类型,所以确定表达式的类型很简单并且工作正常.