このジェネリックコードで、なぜ「引数1:「toplogylibrary.lelationshipbase 」から「trelationship」に変換できません」

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

質問

「引数1:「toplogylibrary.lelationshipbase」から「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 = Relationshipbaseであるが、Trelationshipが関係ベースから継承すると言っているのではありません。

しかし、基本クラスをその子孫に変換することはできません。

だから、あなたは本当にこれが必要です:

List<TRelationship>

また

List<RelationshipBase<TNode>>

これで十分ですか?

または多分あなたのコードを見てください:なぜあなたはこの行を変更してみませんか:

var r = new RelationshipBase<TNode>();

と:

var r = new TRelationship();

??

編集:aakashmが言ったように、私はあなたがtkeyではなくtnodeを意味すると思っていました

他のヒント

あなたの制約 TRelationship 言う RelationshipBase<TKey>. 。あなたはおそらくそれを言うことを意味しましたか RelationshipBase<TNode> ?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top