Com este código de genéricos, por que estou recebendo “Argumento 1: não é possível converter de 'toplogylibrary.relationbase ' para 'Trelationship'"

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

Pergunta

Veja por que estou recebendo um "argumento 1: não posso converter de 'toplogylibrary.relationshipbase' para 'trelationship'" no código abaixo, em CreaterSelation ()?

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


}
Foi útil?

Solução

Com estas linhas:

where TRelationship : RelationshipBase<TNode>, new()

Você não está dizendo que Trelationship = Relationship, mas o TrelationShip herda de uma base de relacionamento.

Mas você não pode implicar converter uma classe base para seu descendente.

Então, você realmente precisa disso:

List<TRelationship>

ou

List<RelationshipBase<TNode>>

isso é suficiente para você?

Ou talvez olhando seu código: por que você não muda esta linha:

var r = new RelationshipBase<TNode>();

com:

var r = new TRelationship();

??

EDIT: Como Aakashm disse que eu supunha que você quis dizer tnode e não tkey

Outras dicas

Sua restrição para TRelationship diz RelationshipBase<TKey>. Você talvez quis dizer isso para dizer RelationshipBase<TNode> ?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top