什麼是 C# 中的密封類?


在 C# 中使用 sealed 關鍵字的 sealed class 不可以繼承。同樣,還可以將 sealed 關鍵字新增到方法中。

在 C# 中對方法使用 sealed 修飾符時,那麼該方法將失去重寫功能。sealed 方法應屬於派生類,並且該方法必須是重寫方法。

我們來看一下 C# 中的 sealed 類的示例 −

示例

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 sealed class Result {
      public string Display() {
         return "Passed";
      }
   }
}

要訪問 sealed 類的成員,我們需要建立物件。在 sealed 類中建立的方法不能繼承 −

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

更新於: 2020 年 6 月 21 日

636 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告