C# 密封类和方法
C# 密封类和方法
在本教程中,我们将通过示例了解 C# 中的密封类和方法。
密封类
在C#中,当我们不希望一个类被另一个类继承时,我们可以将该类声明为密封类 .
密封类不能有派生类。我们使用 sealed
关键字来创建一个密封的类。例如,
using System;
namespace SealedClass {
sealed class Animal {
}
// trying to inherit sealed class
// Error Code
class Dog : Animal {
}
class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog d1 = new Dog();
Console.ReadLine();
}
}
}
在上面的例子中,我们创建了一个密封类 Animal .在这里,我们试图导出 Dog Animal 类 类。
由于密封类不能被继承,程序产生如下错误:
error CS0509: 'Dog': cannot derive from sealed type 'Animal'
密封方法
在方法覆盖期间,如果我们不希望被覆盖的方法被另一个类进一步覆盖,我们可以将其声明为 密封方法 .
我们使用 sealed
带有重写方法的关键字以创建密封方法。例如,
using System;
namespace SealedClass {
class Animal {
public virtual void makeSound() {
Console.WriteLine("Animal Sound");
}
}
class Dog : Animal {
// sealed method
sealed public override void makeSound() {
Console.WriteLine("Dog Sound");
}
}
class Puppy : Dog {
// trying to override sealed method
public override void makeSound() {
Console.WriteLine("Puppy Sound");
}
}
class Program {
static void Main (string [] args) {
// create an object of Puppy class
Puppy d1 = new Puppy();
Console.ReadLine();
}
}
}
在上面的例子中,我们重写了 makeSound() Dog 中的方法 类。
// Inside the Dog class
sealed public override void makeSound() {
Console.WriteLine("Dog Sound");
}
请注意,我们使用了 sealed
makeSound() 的关键字 .这意味着 小狗 继承 Dog 的类 类不允许覆盖 makeSound() .
因此,我们得到一个错误
error CS0239: 'Puppy.makeSound()': cannot override inherited member 'Dog.makeSound()' because it is sealed
当我们尝试进一步覆盖 makeSound() Puppy 中的方法 班级。
注意 :密封一个被覆盖的方法可以防止多级继承中的方法覆盖。
为什么选择密封类?
1.我们使用密封类来防止继承。由于我们不能继承密封类,所以密封类中的方法不能被其他类操作。
它有助于防止安全问题。例如,
sealed class A {
...
}
// error code
class B : A {
...
}
作为类 A 不能被继承,类 B 不能覆盖和操作类 A 的方法 .
2. 密封类的最佳用途之一是当您拥有一个具有静态成员的类时。
笔 System.Drawing
的类 命名空间是密封类的示例之一。 笔 类具有代表具有标准颜色的笔的静态成员。 Pens.Blue
代表一支蓝色的笔。
C语言