Hello!!
Below I have three classes. They are Base, Sub and Test.
Sub is inheriting from Base.
The main issue here is to pass the reference of Test up to the base class
Base.
This work but I hope that somebody can explain more about why this works.
The sequence is the following.
1. Sub is being instansiated from main.
2. c-tor Sub is calling reInit() which is inherited from Base.
3. Method getTest() is being called from reInit which exist in Base.
4. Property Tal is being called from reInit and the int tal is being written
to console.
Now what I find a little hard to understand is how it is possible to call a
method which is below the class you are within.
In this case you are in class Base and call getTest which exist in Base so
why is not the getTest
which exist in Base called instead.
If you for example call getTest() from Sub c-tor I can understand that the
overridden getTest in Sub is called insteadd of getTest in Base.
But when you call methods in Base that also exist in Sub I don't find it so
easy to understand it.
I also know that the keyword virtual and override that make this possible.
I hope somebody can give some good explanation so I don't find it hard to
understand.
public class Base
{
public virtual Test getTest()
{
return null;
}
public void reInit()
{
Console.WriteLine("t.Tal={0}",getTest().Tal);
}
}
public class Sub : Base
{
private Test test = new Test();
public Sub()
{
reInit();
}
public override Test getTest()
{
return test;
}
static void Main()
{
Sub sub = new Sub();
}
}
public class Test
{
private int tal = -1;
public int Tal
{
get {return tal;}
}
}
//Tony