【问题标题】:Interfaces - method returning object of type of the concrete class implementing it接口 - 方法返回实现它的具体类的类型的对象
【发布时间】:2020-06-09 20:46:19
【问题描述】:

考虑一个类:

// partial code for this class
abstract class DataNode : System.IComparable<DataNode>, System.IEquatable<DataNode>, System.Collections.IEnumerable, IDataNode
{
    protected DataNode parent;
    protected int order = System.Int32.MaxValue;

    // ctor
    protected DataNode(DataNode parent, string name)
    {
       modified = new System.Collections.Generic.Dictionary<string, string>();
       original = new System.Collections.Generic.Dictionary<string, string>();
       _parent = parent;
       if (name == null)
       {
           throw new System.ArgumentNullException("name");
       }
       original.Add("name", name);
       _status = Modification_Status.ADDED;
    }

    // methods returning objects of the same type as the class, need to be defined in interface
    public DataNode getParent()
    {
        // return the parent
    }

    public abstract DataNode deepCopy(DataNode parent);
}

在处理实现此接口的类中的方法时会出现问题,这些方法返回与该类相同类型的对象,如上面的两个示例所示。

代码正在重构以进行单元测试。其中一部分是为基类创建接口,例如这个。正在创建一个接口,如下所示:

// partial interface code
public interface IDataNode
{
    // all public methods

    IData_Node deepCopy(IDataNode parent);
    IData_Node getParent();
}

不能在接口中使用DataNode 声明方法,因为返回类型不易访问。如何处理这个问题?

编辑:实际上,使用返回类型和参数声明 IDataNode 而不是 DataNodedeep_copy 方法有效,但似乎代码中所有对此的引用都需要更改。

【问题讨论】:

  • IDataNode 有什么问题你为什么不能使用它?
  • @MichaelRandall 我最终在DataNode 基类中使用了IDataNode,然后将这些方法的引用更新为具体类型,如果这有意义的话。我觉得还可以。

标签: c# .net oop interface


【解决方案1】:

一个常见的方法是这样的:

public interface IDataNode
{

}

public interface IDataNode<T> : IDataNode where T : IDataNode
{
    T deepCopy(T parent);
    T getParent();
}

abstract class DataNode : IDataNode<DataNode>
{
    public abstract DataNode deepCopy(DataNode parent);

    public DataNode getParent()
    {
        throw new NotImplementedException();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-16
    • 2011-06-22
    • 1970-01-01
    • 2016-05-15
    • 2016-01-09
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多