I have a D class inherits from C abstract class and writing to console related message. I expect to see "D" on my console window but it writes "B". I think virtual keyword in C class breaks the rule. I didn't understand why. Can anyone explain?
class Program
{
static void Main(string[] args)
{
A obj = new D();
obj.Write();
Console.Read();
}
}
public abstract class A
{
public virtual void Write()
{
Console.WriteLine("A");
}
}
public abstract class B : A
{
public override void Write()
{
Console.WriteLine("B");
}
}
public abstract class C : B
{
public virtual void Write()
{
Console.WriteLine("C");
}
}
public class D : C
{
public override void Write()
{
Console.WriteLine("D");
}
}
The problem is that C
does not override the function from class A
. The compiler gives you a warning the the new
keyword is required. If you also use override
in class C
, it works like you expected.
Or if you replace A obj = new D();
with D obj = new D();
, you would get the same result.
Your compiler already does a pretty good job here if you listen to it:
warning CS0114:
'C.Write()' hides inherited member 'B.Write()'.
To make the current member override that implementation, add the override keyword.
Otherwise add the new keyword.
The fact that you used virtual
instead of override
on C will result in the default behaviour of new
for this method, breaking the inheritance chain.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.