How can I get a specific base class in inheritance?
I think you are looking at this the wrong way. Every instance in the hierarchy is basically the same type (for example Human
). Instead of inheritance, you are looking at a composition example where each Human
contains links to the others Humans
. Something like that:
public class Node
{
public string Name { get; set; }
/* Other properties */
public Node Parent { get; set; }
public Node Child { get; set; }
}
Example for the population:
Node son = new Node();
Node father = new Node { Child = son };
Node grandFather = new Node { Child = father };
son.Parent = father;
father.Parent = grandFather;
In general, to access some depth of the hierarchy
node.Child.Child.Child .....
node.Parent.Parent.parent ....
To skip generations, you can write a function like:
public Node GetAncestor(int generations)
{
if (generations == 0)
return this;
return Parent?.GetAncestor(generations - 1);
}
//Will retrieve grandFather
var ancesstor = son.GetAncestor(2);
source to share
C # does not provide generate-pass constructors for the inheritance hierarchy to work. If the hierarchy looks like this
GrandGrandFather
|
+--- GrandFather
|
+--- Father
|
+--- Son
then Son
can access Father
using base
, or Father
can access GrandFather
and GrandFather
can access GrandGrandFather
.
Any generation skipping functions must be explicitly built into your classes. For example, if it GrandGrandFather
is to make some of its functionality available to subclasses of its subclasses, it should provide a protected and / or internal method for it.
source to share