In other words, what's the default (if nothing is specified)? I'm guessing the default is virtual, because you can use the "new" keyword to override a base method even when the base method has no virtual specified. If that's the case then why do we even need a Virtual option? Couldn't we just use Sealed when we do need to prevent further inheritance?
C# methods are sealed by default -- you cannot override them without the virtual
keyword.
The new
keyword hides the method in the base class.
Here's what I mean by hiding:
public class HidingA
{
public string Get()
{
return "A";
}
}
public class HidingB : HidingA
{
public new string Get()
{
return "B";
}
}
HidingA a = new HidingA();
HidingB b = new HidingB();
Console.WriteLine(a.Get()); // "A"
Console.WriteLine(b.Get()); // "B"
HidingA c = new HidingB();
Console.WriteLine(c.Get()); // "A". Since we're calling this instance of "B" an "A",
//we're using the "A" implementation.
Now, the Virtual version!
public class VirtualA
{
public virtual string Get()
{
return "A";
}
}
public class VirtualB : VirtualA
{
public override string Get()
{
return "B";
}
}
VirtualA a = new VirtualA();
VirtualB b = new VirtualB();
Console.WriteLine(a.Get()); // "A"
Console.WriteLine(b.Get()); // "B"
VirtualA c = new VirtualB();
Console.WriteLine(c.Get()); // "B". We overrode VirtualB.Get, so it's using the
// "B" implementation of the method
So if we make a method that takes HidingA
as a parameter and pass it an instance of a HidingB
, we're going to get the HidingA
implementation of the Get
method.
MSDN: http://msdn.microsoft.com/en-us/library/6fawty39.aspx
Classes are open for inheritance unless the sealed
keyword is specified.
new
creates a new method (not overriding it), where as an overridden one would replace it, hence being virtual
. As stated above by DanielM, methods are sealed by default.
This is why we need virtual:
class Foo
{
public void Baz() { Assert("Foo.Baz"); }
}
class ChildOfFoo : Foo
{
public new void Baz() { Assert("ChildOfFoo.Baz"); }
}
Foo foo = new ChildOfFoo();
foo.Baz(); // Foo.Baz
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.