Mit diesem Generics -Code bekomme ich "Argument 1: Kann nicht von 'toplogylibrary.RelationshipBase ' in 'Trelationship' konvertiert werden.
-
26-09-2019 - |
Frage
Gibt es im Code unten ein "Argument 1: Ich kann nicht von 'Toplogylibrary. -RelationshipBase' in 'TRELATIONSHIP" konvertieren?
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;
}
}
Lösung
Mit dieser Linie:
where TRelationship : RelationshipBase<TNode>, new()
Sie sagen nicht, dass TRELATIONSHIP = RELATIONBASE, aber Trelationship von einer Beziehung erbt.
Sie können jedoch keine Basisklasse in ihren Nachkomme konvertieren.
Sie brauchen also wirklich:
List<TRelationship>
oder
List<RelationshipBase<TNode>>
Das ist genug für dich?
Oder vielleicht ändern Sie Ihren Code: Warum ändern Sie diese Zeile nicht:
var r = new RelationshipBase<TNode>();
mit:
var r = new TRelationship();
??
Bearbeiten: Wie Aakashm sagte, ich habe angenommen, Sie meinten Tnode und nicht TKY
Andere Tipps
Ihre Einschränkung für TRelationship
sagt RelationshipBase<TKey>
. Hast du vielleicht meinst, es zu sagen RelationshipBase<TNode>
?
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow