c# - 使用 "new"隐藏继承接口(interface) : Is it a good idea? 中的基本成员

标签 c# inheritance interface

是否建议在派生接口(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/

相关文章:

C# - 将接口(interface)转换为备用基类?

perl - 为什么我的排序不能在 Perl 中工作?

Java - 接口(interface)实现中的方法名称冲突

c# - 从 C# 邮件发送中获取输出

c# - 尝试使用自定义验证属性时出现 System.InvalidOperationException

c# - C# 中的不良继承示例

java - 什么是java接口(interface)上的抽象方法

java - RHEL 5 中带有 Files.createSymbolicLink (Java 7) 的符号链接(symbolic link)

c# - 从 C# 中的进程名称获取程序标题

c# - C# boolean 函数并非所有代码都返回值