【发布时间】:2011-10-28 04:39:59
【问题描述】:
考虑以下示例:
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 对象作为 @987654326 @ 大多数时候,从不作为IBase1 或IBase2。这主要是因为IAllYourBase 还具有由AllYourBase 实现的接口方法(我未能在上面的代码sn-p 中详细说明这些方法,因为我认为它们无关紧要)并且我也想访问这些方法。一直来回转换会变得非常乏味并导致代码混乱。
我确实尝试了一种解决方案,该解决方案涉及在 IAllYourBase 中定义 Percentage 属性而不使用显式接口实现,这似乎至少消除了编译器错误:
class IAllYourBase : IBase1, IBase2
{
int Percentage { get; set; }
}
这是一个有效的解决方案吗?
【问题讨论】:
-
+1:恕我直言不应该存在的有趣问题。
-
base即使是局部变量也不是一个好名字,因为它可能与用于从派生类中访问基类成员的base关键字混淆。跨度> -
@Jesse 实际上根本不合法。
base始终是关键字。 -
如果你能提供更多关于你的类结构在这里代表什么的详细信息,它们很有可能被重新设计,你就可以摆脱这个问题
-
@Jesse:我知道这是无效的,这是一个人为的例子。我什至没有编译它。但你明白了我想要表达的基本观点......
标签: c# oop interface ambiguity