Posso fare riferimento a metodi/parametri estesi senza dover lanciare dall'oggetto di classe base restituito

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

Domanda

C'è via per non avere un "cast" il top.first (). Value () ritorna al "nodo", ma piuttosto lo presumo automaticamente (al contrario di nodebase), quindi vedo attributi estesi per la classe I Definire nel nodo?

Cioè c'è un modo per dire:

top.Nodes.First().Value.Path;

Al contrario di dover andare:

((Node)top.Nodes.First().Value).Path)

Grazie

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



}
È stato utile?

Soluzione

In TopologyBase, Cambia il tuo dizionario TValue essere TNode piuttosto che NodeBase<TKey>. top.Nodes.First().Value restituirà quindi un Node nel tuo codice di esempio.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top