如果我尝试从类到接口的无效转换,那么编译器不会抱怨(错误发生在运行时);但是,如果我尝试对抽象类进行类似的强制转换,它确实会抱怨。
class Program
{
abstract class aBaz
{
public abstract int A { get; }
}
interface IBar
{
int B { get; }
}
class Foo
{
public int C { get; }
}
static void Main()
{
Foo foo = new Foo();
// compiler error, as expected, since Foo doesn't inherit aBaz
aBaz baz = (aBaz)foo;
// no compiler error, even though Foo doesn't implement IBar
IBar bar = (IBar)foo;
}
}
为什么编译器不拒绝从Foo到IBar的转换,当它(看似?)无效时?或者,换个问题,如果编译器允许对接口 IBar 进行这种“无效”强制转换,为什么它不允许对抽象类aBaz进行类似的“无效”强制转换?