首先说明一下,通常写代码的时候应该主动避免这种情况发生。
但当这种情况是必要的时候,我们可以用显式实现接口的方式,示例如下:
public interface ITest {
void Test();
}
public interface ITest2 {
void Test();
}
public class Dual : ITest, ITest2
{
void ITest.Test() {
Console.WriteLine("ITest.Test");
}
void ITest2.Test() {
Console.WriteLine("ITest2.Test");
}
}
并且,这时候这两个方法对于类来说不是public的方法了。要调用这两个方法,需要先将类对象cast成对应的接口类型。示例如下。
var dual = new Dual();
// Call the ITest.Test() function by first assigning to an explicitly typed variable
ITest test = dual;
test.Test();
// Call the ITest2.Test() function by using a type cast.
((ITest2)dual).Test();
声明:以上代码来自StackOverflow一个相关问题的回答。