如果我尝试从类到接口的无效转换,那么编译器不会抱怨(错误发生在运行时);它确实抱怨,但是,如果我尝试类似演员抽象类。为什么没有编译器错误,当我将一个类转换为它没有实现的接口?
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;
}
}
为什么不编译器拒绝来自富到伊巴尔投,当它的(貌似?)无效?或者,如果编译器允许这个“无效”强制转换到接口IBar,为什么它不允许类似的“无效”强制转换为抽象类aBaz?
http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx – SLaks
这个铸造到一个接口位在我今晚的对接......和男孩它受伤了。 –
您没有将'Foo'标记为'sealed'。因此,明确的演员应编制。可能存在一个从'Foo'继承的类,它还执行'IBar'。如果你使用'密封类Foo',在编译时对'IBar'的转换是非法的。 (在这种情况下,类Foo是嵌套的,所以即使必须允许强制转换,也可以设想C#编译器可以给出_warning_(不是错误,因为该规范说显式转换存在),因为它可以看到嵌套类的全部范围,但这可能是一种罕见的情况。)_编辑:_我现在看到这在下面的阿列克谢覆盖。 –