这是一个解释我的问题的简化示例 - 我试图通过将通用接口(interface)派生为具有如下具体类型的接口(interface)来提高显式实现的通用接口(interface)的代码可读性:interface ITyped : IGeneric<string>
.这个想法是不必使用 IGeneric<string>
在所有已实现的显式方法名称中。
所以代码会这样写:
ITyped.M1(string p){}
ITyped.M2(string p){}
代替
IGeneric<string>.M1(string p){}
IGeneric<string>.M2(string q){}
想象一个具有多个泛型类型的接口(interface)来理解我为什么要这样做。
现在的问题是:这行不通!编译器抛出一个错误,指出我的声明不是接口(interface)的成员。我必须明确地使用带有泛型声明的基接口(interface)。如果这行得通,难道没有意义吗?进一步的尝试表明,甚至不需要泛型——一个简单的派生接口(interface)也不允许在派生接口(interface)中显式实现基接口(interface)的继承方法。我想了解为什么不允许这样做的理论。
是否有其他方法可以提高这种情况的可读性?
完整的示例代码在这里:
interface IGeneric<T>
{
void M(T t);
}
interface ITyped: IGeneric<string> { }
class C : ITyped
{
//Explicit declaration with base interface - OK
void IGeneric<string>.M(string t) {}
//Implicit declaration - OK
public void M(string t){ }
//Explicit declaration with derived interface - Error!
void ITyped.M(string t) {} //Error CS0539
}
最佳答案
在提示 c# 语言规范和 CodesInChaos 对另一个答案的评论后,我找到了不允许这样做的原因:
设想第二个派生接口(interface) IDerived2: IBase
和一个实现两个派生接口(interface)的具体类,我将能够创建两个不明确的实现
private interface IBase
{
void M();
}
class C : IDerived1, IDerived2
{
//Which method should now be called when using IBase.M?
void IDerived1.M() {}
void IDerived2.M() {}
}
所以正是多重继承限制了我们使用派生的显式接口(interface)声明。通过强制使用基声明,在多重继承的情况下,编译器确保只能有一个实现,从而有效地防止我们做坏事。
解决方法是不显式实现接口(interface),而是隐式实现——实际上我显式实现它还有另一个原因,但总的来说,隐式声明将是一种有效的解决方法。
关于c# - 为什么不允许在派生接口(interface)上显式实现基接口(interface)的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928762/