为什么当我将一个类转换为它没有实现的接口时没有编译器错误? [英] Why no compiler error when I cast a class to an interface it doesn't implement?

查看:27
本文介绍了为什么当我将一个类转换为它没有实现的接口时没有编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试从一个类到一个接口的无效转换,那么编译器不会抱怨(错误发生在运行时);但是,如果我尝试对抽象类进行类似的转换,它确实会抱怨.

If I try an invalid cast from a class to an interface, then the compiler doesn't complain (the error occurs at runtime); it does complain, however, if I try a similar cast to an abstract class.

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;
    }
}

为什么编译器不拒绝从 FooIBar 的强制转换,当它(似乎?)无效时?或者,换一个问题,如果编译器允许将这个无效"转换为接口 IBar,为什么它不允许将类似的无效"转换为抽象类 aBaz?

Why doesn't the compiler reject the cast from Foo to IBar, when it's (seemingly?) invalid? Or, to flip the question, if the compiler allows this "invalid" cast to the interface IBar, why doesn't it allow the similar "invalid" cast to the abstract class aBaz?

推荐答案

您需要了解 .Net 的继承系统才能明白为什么这样做有意义.在 .Net 中,一个类只能从一个基类继承,但可以实现任意数量的接口.

You need to understand the inheritance system of .Net to see why this makes sense. In .Net, a class may inherit from only one base class but may implement any number of interfaces.

class Program
{
    abstract class aBaz
    {
        public abstract int A { get; }
    }

    interface IBar
    {
        int B { get; }
    }

    class Foo
    {
        public int C { get; }
    }

    class BarableFoo : Foo, IBar
    {
        public int C { get; }
    }

    static void Main()
    {
        // This is why the compiler doesn't error on the later cast
        Foo foo = new BarableFoo();

        // compiler error: aBaz is a class and the compiler knows that
        // Foo is not a _subclass_ of aBaz.
        aBaz baz = (aBaz)foo;

        // no compiler error: the class Foo does not implement IBar, however at runtime
        // this instance, "foo", might be a subclass of Foo that _implements_ IBar.
        // This is perfectly valid, and succeeds at runtime.
        IBar bar = (IBar)foo;

        // On the other hand...
        foo = new Foo();

        // This fails at runtime as expected. 
        bar = (IBar)foo;
    }

}

在问题中极其简单的原始示例中,编译器似乎可以检测到这个 foo 实例永远不会可转换为 IBar,但这更像是一个很好的"警告,而不是一个问题语言正确.

In the extremely simple original example in the question, it seems like the compiler could detect that this instance of foo is never going to be castable to IBar, but that is more of a "nice to have" warning than a matter of language correctness.

这篇关于为什么当我将一个类转换为它没有实现的接口时没有编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆