使用此通用代码,为什么我会得到“参数1:不能从'toplogylibrary.relationshipbase '转换为'trelationship'”
-
26-09-2019 - |
题
看到了为什么我在下面的代码()中获得“参数1:无法从'toplogylibrary.Realationhiphiphips”转换为'trelationship'”?
public class TopologyBase<TKey, TNode, TRelationship>
where TNode : NodeBase<TKey>, new()
where TRelationship : RelationshipBase<TKey>, new()
{
// Properties
public Dictionary<TKey, TNode> Nodes { get; private set; }
public List<TRelationship> Relationships { get; private set; }
// Constructors
protected TopologyBase()
{
Nodes = new Dictionary<TKey, TNode>();
Relationships = new List<TRelationship>();
}
// Methods
public TNode CreateNode(TKey key)
{
var node = new TNode {Key = key};
Nodes.Add(node.Key, node);
return node;
}
public void CreateRelationship(TNode parent, TNode child)
{
// Validation
if (!Nodes.ContainsKey(parent.Key) || !Nodes.ContainsKey(child.Key))
{
throw new ApplicationException("Can not create relationship as either parent or child was not in the graph: Parent:" + parent.Key + ", Child:" + child.Key);
}
// Add Relationship
var r = new RelationshipBase<TNode>();
r.Parent = parent;
r.Child = child;
Relationships.Add(r); // *** HERE *** "Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase<TNode>' to 'TRelationship'"
}
}
public class RelationshipBase<TNode>
{
public TNode Parent { get; set; }
public TNode Child { get; set; }
}
public class NodeBase<T>
{
public T Key { get; set; }
public NodeBase()
{
}
public NodeBase(T key)
{
Key = key;
}
}
解决方案
与这些行:
where TRelationship : RelationshipBase<TNode>, new()
您并不是说Trelationship =关系基础,而是从关系基础继承的Trelationship。
但是您不能将基类转换为其后代。
因此,您确实需要这个:
List<TRelationship>
或者
List<RelationshipBase<TNode>>
这对您来说足够了吗?
或者查找您的代码:为什么不更改此行:
var r = new RelationshipBase<TNode>();
和:
var r = new TRelationship();
??
编辑:正如Aakashm所说
其他提示
您的约束 TRelationship
说 RelationshipBase<TKey>
. 。你也许是说 RelationshipBase<TNode>
?
不隶属于 StackOverflow