是否建议在派生接口(interface)中使用“new”关键字为具有相同名称的属性或方法提供更派生的返回值?
假设我有一个接口(interface) IDocument:
public interface IDocument
{
IParagraphs Paragraphs { get; }
IRevisions Revisions { get; }
IStyles Styles { get; }
}
还有一个派生的IRtfDocument。
public interface IRtfDocument: IDocument
{
string Rtf { get; }
...
}
我还有更多用于 IParagraphs、IRevisions 和 IStyles 的派生接口(interface):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# 老手来运行它。
更新:所以我实际上继续尝试使用我的界面中描述的"new"。我的 RtfDocument 类最终需要 IDocument.Styles 属性和 IRtfDocument.Styles 属性。虽然我可以让 IDocument.Styles 属性返回 IRtfDocument.Styles 的值,但感觉不太正确,因为我正在实现两个属性。
似乎 编译器没有说明 IRtfStyles 派生自 IStyles 这一事实,所以它坚持认为我两者都有。如果 Liskov Substitution Principle 就好了让我在 RtfDocument 类中实现 IRtfDocument.Styles。
最佳答案
更简单的解决方案可能只是拥有一个通用接口(interface):
public interface IFooBox<T>
where T : IFoo
{
T Foo { get; }
}
然后你可以得到一个 IFooBox<IFoo>
用于您的基本对象,或 IFooBox<IEnhancedFoo>
为增强版。
关于c# - 使用 "new"隐藏继承接口(interface) : Is it a good idea? 中的基本成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16112353/