C# 中的密封类是什么?

csharpprogrammingserver side programming更新于 2025/10/13 20:37:17

C# 中带有 seal 关键字的密封类不能被继承。同样,sealed 关键字可以添加到方法中。

在 C# 中,如果在方法上使用 seal 修饰符,则该方法将失去重写功能。密封方法应该是派生类的一部分,并且该方法必须是被重写的方法。

让我们看一个 C# 中密封类的示例 −

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Result ob = new Result();
         string str = ob.Display();

         Console.WriteLine(str);
         Console.ReadLine();
      }
   }

   public seal class Result {
      public string Display() {
         return "Passed";
      }
   }
}

要访问密封类的成员,我们需要创建对象。在密封类中创建的方法不能被继承 −

public sealed class Result {
   public string Display() {
      return "Passed";
   }
}

相关文章