在 C# 中,什麼是密封類?


具有 sealed 關鍵字的 C# 中的 sealed 類不能被繼承。以同樣的方法,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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.