考虑以下示例:
interface IBase1
{
int Percentage { get; set; }
}
interface IBase2
{
int Percentage { get; set; }
}
interface IAllYourBase : IBase1, IBase2
{
}
class AllYourBase : IAllYourBase
{
int percentage;
int Percentage {
get { return percentage; }
set { percentage = value; }
}
}
void Foo()
{
IAllYourBase iayb = new AllYourBase();
int percentage = iayb.Percentage; // Fails to compile. Ambiguity between 'Percentage' property.
}
在上面的示例中,存在调用哪个Percentage
属性的歧义。假设IBase1
和IBase2
接口可能不会被改变,我该如何以最干净、最优选的方式解决这个歧义?
更新
基于使用显式接口实现会得到的回复,我想提到一点:虽然这确实解决了问题,但对于我来说并不是最理想的解决方式,因为我大部分时间都将我的AllYourBase
对象用作IAllYourBase
,很少用作IBase1
或IBase2
。这主要是因为IAllYourBase
也有实现了的接口方法(我在上面的代码片段中没有详细说明它们,因为我认为它们与问题无关),而我也想访问这些方法。反复转换类型将变得非常乏味,并导致混乱的代码。我尝试了一种解决方案,涉及在
IAllYourBase
中定义Percentage
属性,并且不使用显式接口实现,这似乎至少消除了编译器错误。class IAllYourBase : IBase1, IBase2
{
int Percentage { get; set; }
}
这是一个有效的解决方案吗?
base
始终是一个关键字。 - dlev