我可以参考扩展方法/参数,而无需从返回的基类对象施放
-
26-09-2019 - |
题
是否有没有“ cast” top.first()。value()返回“ node”,而是让它自动假设(而不是Nodebase),因此我然后看到类i的扩展属性在节点中定义?
那就是有办法说:
top.Nodes.First().Value.Path;
而不是现在必须去:
((Node)top.Nodes.First().Value).Path)
谢谢
[TestMethod()]
public void CreateNoteTest()
{
var top = new Topology();
Node node = top.CreateNode("a");
node.Path = "testpath";
Assert.AreEqual("testpath", ((Node)top.Nodes.First().Value).Path); // *** HERE ***
}
class Topology : TopologyBase<string, Node, Relationship>
{
}
class Node : NodeBase<string>
{
public string Path { get; set; }
}
public class NodeBase<T>
{
public T Key { get; set; }
public NodeBase()
{
}
public NodeBase(T key)
{
Key = key;
}
}
public class TopologyBase<TKey, TNode, TRelationship>
where TNode : NodeBase<TKey>, new()
where TRelationship : RelationshipBase<TKey>, new()
{
// Properties
public Dictionary<TKey, NodeBase<TKey>> Nodes { get; private set; }
public List<RelationshipBase<TKey>> Relationships { get; private set; }
}
解决方案
在 TopologyBase
, ,更改您的字典 TValue
成为 TNode
而不是 NodeBase<TKey>
. top.Nodes.First().Value
然后将返回 Node
在您的示例代码中。
不隶属于 StackOverflow