Con questo codice generico perché sto ottenendo "Argomento 1: Impossibile convertire da" topLogylibrary.relationshipbase in "tralationship" "

StackOverflow https://stackoverflow.com/questions/2832294

Domanda

Qualunque cosa perché sto ricevendo un "argomento 1: non riesco a convertire da" toplogybrary.relationshipbase "in" tralationship "" nel codice seguente, in CreateRelationship ()?

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;
    }      


}
È stato utile?

Soluzione

Con queste righe:

where TRelationship : RelationshipBase<TNode>, new()

Non stai dicendo che Trelationship = Relationshipbase ma Trelationship eredita da una base di relazioni.

Ma non puoi implicizzare convertire una classe di base al suo discendente.

Quindi, hai davvero bisogno di questo:

List<TRelationship>

o

List<RelationshipBase<TNode>>

questo è abbastanza per te?

O forse cercare il tuo codice: perché non cambi questa riga:

var r = new RelationshipBase<TNode>();

insieme a:

var r = new TRelationship();

??

EDIT: Come ha detto Aakashm, ho supposto che intendessi tnode e non tkey

Altri suggerimenti

Il tuo vincolo per TRelationship dice RelationshipBase<TKey>. Forse intendevi dire RelationshipBase<TNode> ?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top