I've found in the Troelsen's book, that operator sealed can be used on the members of the class to protect virtual methods from the override .
But if I don't want to override a virtual methods, what sense to make it virtual ?
You might have a situation like this:
public class A
{
public virtual void MyMethod()
{
//...
}
}
public class B : A
{
public override void MyMethod()
{
//...
}
}
public class C : B
{
public override void MyMethod()
{
//...
}
}
But what if you want for the inheriting class C
NOT to be able to override B
's MyMethod
, while still allowing B
to override A
's? Then you can do:
public class B : A
{
public sealed override void MyMethod()
{
//...
}
}
With this change made, you can no longer override the method in C
.
In this context, consider the following example:
public class A
{
public virtual void SomeMethod() { }
}
public class B : A
{
public sealed override void SomeMethod() { }
}
public class C : B
{
public override void SomeMethod() { }
}
In this example, without the use of the sealed
keyword on SomeMethod
in class B
, class C
would be able to override it because it's original declaration was as virtual
. The sealed
keyword in this context generates a compiler error. See the MSDN for more information .
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.