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`。在这里,我们尝试从 `Animal` 类派生 `Dog` 类。

由于密封类不能被继承,程序会生成以下错误:

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(); } } }

在上面的示例中,我们在 `Dog` 类中重写了 `makeSound()` 方法。

// Inside the Dog class
sealed public override void makeSound() {
  Console.WriteLine("Dog Sound");
}

请注意,我们对 `makeSound()` 使用了 `sealed` 关键字。这意味着继承 `Dog` 类的 `Puppy` 类不允许重写 `makeSound()`。

因此,我们得到一个错误:

error CS0239: 'Puppy.makeSound()': cannot override inherited member 'Dog.makeSound()' because it is sealed

当我们尝试在 `Puppy` 类中进一步重写 `makeSound()` 方法时。

注意:密封重写方法会阻止在多级继承中进行方法重写。


为什么使用密封类?

1. 我们使用密封类来阻止继承。由于我们不能从密封类继承,密封类中的方法不能被其他类操作。

这有助于防止安全问题。例如:

sealed class A { 
  ...
}

// error code
class B : A {
  ...
}

由于类 `A` 不能被继承,类 `B` 就不能重写和操作类 `A` 的方法。

2. 密封类的一个最佳用途是当你有一个包含静态成员的类时。

`System.Drawing` 命名空间中的 `Pens` 类是密封类的一个例子。`Pens` 类包含表示标准颜色画笔的静态成员。`Pens.Blue` 代表一个蓝色的画笔。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战