考虑以下示例:
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
还有接口方法(我没有在上面的代码片段中详细说明这些方法,因为我认为它们无关紧要),AllYourBase
并且我也想访问它们。一直来回转换会变得非常乏味并导致代码混乱。
我确实尝试了一种解决方案,其中涉及定义Percentage
属性IAllYourBase
而不使用显式接口实现,这似乎至少消除了编译器错误:
class IAllYourBase : IBase1, IBase2
{
int Percentage { get; set; }
}
这是一个有效的解决方案吗?