C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# 封装

C# 封装

封装是将数据包装到单个单元中的概念。它将数据成员和成员函数收集到一个称为类的单元中。封装的目的是防止外部数据被篡改。此数据只能由类的 getter 函数访问。
完全封装的类具有用于读取和写入数据的 getter 和 setter 函数。该类不允许直接访问数据。
在这里,我们正在创建一个示例,其中我们有一个类,该类封装了属性并提供了 getter 和 setter 函数。

示例

namespace AccessSpecifiers
{
    class Student
    {
        // Creating setter and getter for each property
        public string ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}
using System;
namespace AccessSpecifiers
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student();
            // Setting values to the properties
            student.ID = "101";
            student.Name = "Mohan Ram";
            student.Email = "mohan@example.com";
            // getting values
            Console.WriteLine("ID = "+student.ID);
            Console.WriteLine("Name = "+student.Name);
            Console.WriteLine("Email = "+student.Email);
        }
    }
}
输出:
ID = 101
Name = Mohan Ram
Email = "/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e9ebece5eac4e1fce5e9f4e8e1aae7ebe9">[email protected]

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4