new method declaration in derived interface

笑着哭i 提交于 2021-02-04 21:10:30

问题


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

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. If this matters, these interface declarations also have the following attributes: ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown) and Guid(...).


回答1:


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.

For example:

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


来源:https://stackoverflow.com/questions/15311923/new-method-declaration-in-derived-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!