Код: Выделить всё
public class Node{
public Node NextNode{get; set;}
public static Node WithData(T data) => new Node(data);
}
public class Node: Node{
public T Data{get; set;}
public Node(T data) => Data = data;
}
Код: Выделить всё
var node1 = Node.WithData(73); // the node contains an int
var node2 = Node.WithData("Good luck!"); // the node contains a string
node1.NextNode = node2; // chaining the nodes
Notify(node1.Data == 73)); // displays "true" (method Notify() omitted for brevity)
Notify(node1.NextNode.GetType()); // displays "Node`1[System.String]"
Notify(node1.NextNode.Data == "Good luck!");
//compile error: 'Node' does not contain a definition for 'Data'
Я могу решить проблему, выполнив обратное приведение к Node (проверка типа опущена для краткость):
Код: Выделить всё
Notify(((Node)node.NextNode).Data);
// verbose and the casting type is usually not known at compile time
Код: Выделить всё
Notify(((dynamic)node.NextNode).Data); // slow, but works fine at runtime
Код: Выделить всё
if(node.NextNode is Node stringNode) Notify(stringNode.Data);
else if(node.NextNode is Node intNode) Notify(intNode.Data);
// else if... etc.
// bad for maintenance, verbose, especially with many data types
- Есть ли более подходящий способ понизить Node до Node (желательно во время выполнения?
< li>Есть ли лучший подход или лучший дизайн двух классов, чтобы избежать или автоматизировать принижение?
Подробнее здесь: https://stackoverflow.com/questions/793 ... ived-class