Con este código de genéricos, ¿por qué estoy obteniendo "Argumento 1: No puedo convertir de 'ToplogyLibrary.relationshipBase ' a 'Trelationship'"

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

Pregunta

¿Alguna ver por qué obtengo un "Argumento 1: no se puede convertir de 'ToplogyLibrary.RelationshipBase' a 'Trelationship'" en el código a continuación, en CreeaterLationship ()?

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


}
¿Fue útil?

Solución

Con esta línea:

where TRelationship : RelationshipBase<TNode>, new()

No estás diciendo que la trelación = base de relación pero la trelación hereda de una base de relaciones.

Pero no puede implicidad convertir una clase base a su descendiente.

Entonces, realmente necesitas esto:

List<TRelationship>

o

List<RelationshipBase<TNode>>

¿Esto es suficiente para ti?

O tal vez mirando su código: ¿Por qué no cambia esta línea?

var r = new RelationshipBase<TNode>();

con:

var r = new TRelationship();

??

EDITAR: Como dijo Aakashm, suponía que te refieres a Tnode y no a TKey

Otros consejos

Tu restricción por TRelationship dice RelationshipBase<TKey>. ¿Quizás quisiste decir? RelationshipBase<TNode> ?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top