问题
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