什麼是 C# 中的封裝?


C# 中的封裝阻止對實現細節的訪問。使用訪問限定符在 C# 中實現封裝。

C# 支援以下訪問限定符 -

  • 公共
  • 私有
  • 受保護
  • 內部
  • 受保護的內部

可以透過允許類對其他函式和物件隱藏其成員變數和成員函式的私有訪問限定符示例來理解封裝。

在以下示例中,我們具有分配了私有訪問限定符的變數長度和寬度 -

示例

 線上演示

using System;

namespace RectangleApplication {
   class Rectangle {
      private double length;
      private double width;

      public void Acceptdetails() {
         length = 10;
         width = 15;
      }

      public double GetArea() {
         return length * width;
      }

      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }

   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine();
      }
   }
}

輸出

Length: 10
Width: 15
Area: 150

更新時間: 2020 年 6 月 20 日

368 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.