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

TRelationship你对说的约束RelationshipBase<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 所说,我假设您的意思是 TNode 而不是 TKey

于 2010-05-14T06:50:18.650 回答