C# 中的接口多态性

本文关键字:多态性 接口 | 更新日期: 2023-09-27 18:34:02

我有这样的代码:

public interface INode
{
    INode Parent { get; set; }
    // ......
}
public interface ISpecificNode : INode
{
    new ISpecificNode Parent { get; set; }
    // ......
}
public class SpecificNode : ISpecificNode
{
    ISpecificNode Parent { get; set; }
    // ......
}

此代码给出编译错误,因为未实现 INode.Parent。但是,我不需要重复的父属性。
如何解决此问题?

C# 中的接口多态性

我想你正在寻找这样的东西:

public interface INode<T> where T : INode<T>
{
    T Parent { get; set; }
}
public interface ISpecificNode : INode<ISpecificNode>
{
}
public class SpecificNode : ISpecificNode
{
    public ISpecificNode Parent { get; set; }
}

这不是像类那样的继承/覆盖 - 接口不继承其他接口,它们实现它们。

这意味着任何实现ISpecificNode的东西也必须实现INode

我建议你删除这条线

new ISpecificNode Parent { get; set; }

可能没有必要。或者,您可以在抽象基类上实现INode,使用具体的SpecificNode类重写它,并使用属性隐藏来隐藏属性的INode版本。