【发布时间】:2013-04-19 19:40:54
【问题描述】:
是否建议在派生接口中使用“new”关键字来为具有相同名称的属性或方法提供更多派生的返回值?
假设我有一个接口 IDocument:
public interface IDocument
{
IParagraphs Paragraphs { get; }
IRevisions Revisions { get; }
IStyles Styles { get; }
}
并派生出一个 IRtfDocument。
public interface IRtfDocument: IDocument
{
string Rtf { get; }
...
}
我还有更多派生的 IParagraphs、IRevisions 和 IStyles 接口:IRtfParagraphs、IRtfRevisions、IRtfStyles。许多特定于 RTF 的需求推动了他们的创作。
当我访问 RTF 文档的段落时,我希望避免将它们转换为 IRtfParagraphs。修订和样式相同。最好避免同时使用“IRtfParagraphs”和“IParagraphs”。所以我喜欢做的是:
public interface IRtfDocument : IDocument
{
new IRtfParagraphs Paragraphs { get; }
new IRtfRevisions Revisions { get; }
new IRtfStyles Styles { get; }
string Rtf { get; }
}
这被认为是好的做法吗?它似乎适合这种情况,但我想由你们 C# 老手来运行它。
更新:所以我实际上继续尝试使用我的界面中描述的“新”。我的 RtfDocument 类最终需要一个 IDocument.Styles 属性和一个 IRtfDocument.Styles 属性。虽然我可以让 IDocument.Styles 属性返回 IRtfDocument.Styles 的值,但我在实现两个属性时感觉不太对。
它似乎编译器没有考虑到 IRtfStyles 派生自 IStyles 的事实,所以它坚持认为我两者都有。如果Liskov Substitution Principle 让我在 RtfDocument 类中实现 IRtfDocument.Styles 就好了。
【问题讨论】:
-
哎呀,让我修复这个例子,我的错。
-
PS,在我有机会解决问题之前退出投票关闭我。谢谢。
-
@System.Cats.Lol 投票结束意味着问题应该被关闭。如果对问题进行了编辑,使其不再关闭,则可以重新打开。
标签: c# inheritance interface