1

CreateRelationship()で、以下のコードで「引数1:「ToplogyLibrary.RelationshipBase」から「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;
    }      


}
4

2 に答える 2

2

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

于 2010-05-14T06:51:23.937 に答える
1

これらの行で:

where TRelationship : RelationshipBase<TNode>, new()

TRelationship = RelationshipBaseと言っているのではなく、TRelationshipはRelationshipBaseから継承しています。

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

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

List<TRelationship>

また

List<RelationshipBase<TNode>>

これで十分ですか?

または、コードを調べてみてください。この行を変更してみませんか。

var r = new RelationshipBase<TNode>();

と:

var r = new TRelationship();

??

編集:AakashMが言ったように、私はあなたがTKeyではなくTNodeを意味していると思っていました

于 2010-05-14T06:50:18.650 に答える