【问题标题】:new method declaration in derived interface派生接口中的新方法声明
【发布时间】:2013-03-09 14:41:31
【问题描述】:

我最近研究了一些代码,遇到了一个派生接口,它声明了 new 方法,其名称和签名与基本接口完全相同:

public interface IBase
{
    Result Process(Settings settings);
}

public interface IDerived : IBase
{
    new Result Process(Settings settings);
}

我想知道这是否有原因。根据我的理解,我可以安全地删除后一个方法声明并将IDerived 留空,而不会破坏任何使用它的代码。我错了吗?

附:如果这很重要,这些接口声明还具有以下属性:ComVisible(true)InterfaceType(ComInterfaceType.InterfaceIsIUnknown)Guid(...)

【问题讨论】:

    标签: c# .net com-interop


    【解决方案1】:

    好吧,您也许可以摆脱它 - 但如果您摆脱 IDerived 中的方法,严格来说,它实际上并不相同。一个实现实际上可以提供两种不同的方法来不同地实现这两种接口方法。

    例如:

    using System;
    
    public interface IBase
    {
        void Process();
    }
    
    public interface IDerived : IBase
    {
        new void Process();
    }
    
    public class FunkyImpl : IDerived
    {
        void IBase.Process()
        {
            Console.WriteLine("IBase.Process");
        }
    
        void IDerived.Process()
        {
            Console.WriteLine("IDerived.Process");
        }
    }
    
    class Test
    {
        static void Main()
        {
            var funky = new FunkyImpl();
            IBase b = funky;
            IDerived d = funky;
            b.Process();
            d.Process();
        }
    }
    

    【讨论】:

    • 谢谢你,乔恩。所以我会稍微调整一下我的问题:如果我删除 IDerived.Process 方法并且使用它的所有代码都将编译,理论上是否有可能在代码中引入一些运行时错误?
    • @user835103:如果所有代码仍然可以编译(所有代码都实现和使用接口),那么应该没问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2014-02-02
    • 1970-01-01
    • 2017-05-12
    • 2012-09-01
    • 1970-01-01
    • 2010-12-12
    相关资源
    最近更新 更多