c# - 派生类重新实现接口(interface)时如何调用基接口(interface)实现?

标签 c# .net inheritance interface

因此,出于某种原因,我正在测试 C# 和 .NET VM 的限制。我遇到了一些令人困惑的行为。

采用这些类和接口(interface):

public interface ITest
{
    void Test();
    void Test2();
}
public abstract class Base : ITest
{
    void ITest.Test()
    {
        Console.WriteLine("base");
    }
    public void Test2()
    {
        Console.WriteLine("base2");
    }
    public void Test3()
    {
        Console.WriteLine("base3");
    }
}
public class Impl : Base, ITest
{
    void ITest.Test()
    {
        Console.WriteLine("impl");
    }
    void ITest.Test2()
    {
        Console.WriteLine("impl2");
    }
    public void Test3()
    {
        Console.WriteLine("impl3");
    }
}

然后像这样使用它们:

        var i = new Impl();
        var b = (Base)i;
        var itest1 = (ITest)i;
        var itest2 = (ITest)b;
        itest1.Test();
        itest2.Test();
        itest1.Test2();
        itest2.Test2();
        i.Test2();
        b.Test2();
        i.Test3(); //for reference, a standard non-virtual method outside of an interface
        b.Test3();

我希望输出看起来像这样:

impl
base
impl2
base2
impl2
base2
impl3
base3

当然,事情不可能那么简单。所以,实际的输出是这样的:

impl
impl
impl2
impl2
base2
base2
impl3
base3

除了这种疯狂的怪异行为之外,是否可以访问 Base.Test() 实现?

最佳答案

也许你应该检查为什么你发现结果很奇怪。对我来说,看起来你得到了你所实现的。

没有办法获取Base.Test,因为没有Base.Test。您需要通过接口(interface)显式访问它,然后它不再是 Base,而是 Impl,因为底层真实对象不是 Base 类型.

关于c# - 派生类重新实现接口(interface)时如何调用基接口(interface)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23393329/

相关文章:

c# - 在 WPF 中使用数据绑定(bind)刷新 UI

c# - 在 MSBuild 的解决方案中循环项目

.net - .NET core 如何在多种环境中运行?

typescript - 继承异常和instanceof

c# - 使用 WCF 服务在 .NET 中禁用 X.509 证书验证

c# webClient.DownloadFile 不下载,它只是创建一个空文本文件

.net - .NET 中的异步 WMI 事件处理

c# - 如何将集合的子集传递给 C# 方法?

java - 在 IntelliJ 中,查看类/接口(interface)的所有后代的快捷方式?

java - 对应类型树