首页  >  文章  >  后端开发  >  C#中的封装是如何实现的?

C#中的封装是如何实现的?

WBOY
WBOY转载
2023-09-04 23:17:021296浏览

C#中的封装是如何实现的?

封装是通过使用访问说明符来实现的。访问说明符定义类成员的范围和可见性。 C#支持以下访问说明符:Public、Private、Protected、Internal、Protected Internal等。

封装可以通过私有访问说明符来理解,它允许类隐藏其成员变量和成员来自其他函数和对象的函数。

在下面的示例中,我们将长度和宽度作为分配私有访问说明符的变量 -

示例

using System;

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

      public void Acceptdetails() {
         length = 20;
         width = 30;
      }

      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();
      }
   }
}

以上是C#中的封装是如何实现的?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除