C# 中的封装是什么?

csharpprogrammingserver side programming更新于 2025/10/15 7:52:17

C# 中的封装阻止访问实现细节。使用访问说明符在 C# 中实现封装。

以下是 C# 支持的访问说明符 −

  • Public
  • Private
  • Protected
  • Internal
  • Protected internal

我们可以通过 private 访问说明符的例子来理解封装,该说明符允许类向其他函数和对象隐藏其成员变量和成员函数。

在下面的例子中,我们将长度和宽度作为变量赋值给 private 访问说明符 −

示例

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

相关文章