【发布时间】: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 而不是 DataNode 的 deep_copy 方法有效,但似乎代码中所有对此的引用都需要更改。
【问题讨论】:
-
IDataNode有什么问题你为什么不能使用它? -
@MichaelRandall 我最终在
DataNode基类中使用了IDataNode,然后将这些方法的引用更新为具体类型,如果这有意义的话。我觉得还可以。