派生接口中的新方法声明 [英] new method declaration in derived interface

查看:53
本文介绍了派生接口中的新方法声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I lately studied some code and encountered a derived interface that declares new method with exactly the same name and signature as a base interface:

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

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

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

I'm wondering if there could be a reason for this. According to my understanding I can safely remove the latter method declaration and leave IDerived empty without possibly breaking any code using it. Am I wrong?

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

P.S. If this matters, these interface declarations also have the following attributes: ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown) and Guid(...).

推荐答案

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

Well, you may be able to get rid of it - but if you get rid of the method in IDerived, it's not actually the same, strictly speaking. An implementation can actually provide two different methods to implement the two interface methods differently.

例如:

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

这篇关于派生接口中的新方法声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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