How can you prevent a class from overriding in C#?
How can you prevent a class from overriding in C#?
To prevent a class from being overridden in C#, you can use the sealed
keyword. Here's how you can apply it:
To prevent a class from being inherited, simply add the sealed
keyword before the class
keyword:
public sealed class MyClass
{
// Class members
}
By marking a class as sealed
, you ensure that no other class can inherit from it. If another class attempts to inherit from a sealed class, the compiler will throw an error.
You can also seal a virtual method within a class to prevent it from being overridden in derived classes. To do this, add the sealed
keyword before the override
keyword when overriding the virtual method:
public class BaseClass
{
public virtual void MyMethod()
{
// Method implementation
}...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào