封装定义为将数据包装在单个单元下。它是将代码及其处理的数据绑定在一起的机制。以另一种方式,封装是一种保护性屏蔽,可防止该屏蔽之外的代码访问数据。
- 从封装技术上讲,一个类的变量或数据对任何其他类都是隐藏的,并且只能通过声明了它们的自身类的任何成员函数来访问。
- 与封装一样,一个类中的数据对其他类是隐藏的,因此也称为数据隐藏。
- 可以通过以下方式实现封装:将类中的所有变量声明为私有,并使用类中的C#属性设置和获取变量的值。
例子:
// C# program to illustrate encapsulation
using System;
public class DemoEncap {
// private variables declared
// these can only be accessed by
// public methods of class
private String studentName;
private int studentAge;
// using accessors to get and
// set the value of studentName
public String Name
{
get
{
return studentName;
}
set
{
studentName = value;
}
}
// using accessors to get and
// set the value of studentAge
public int Age
{
get
{
return studentAge;
}
set
{
studentAge = value;
}
}
}
// Driver Class
class GFG {
// Main Method
static public void Main()
{
// creating object
DemoEncap obj = new DemoEncap();
// calls set accessor of the property Name,
// and pass "Ankita" as value of the
// standard field 'value'
obj.Name = "Ankita";
// calls set accessor of the property Age,
// and pass "21" as value of the
// standard field 'value'
obj.Age = 21;
// Displaying values of the variables
Console.WriteLine("Name: " + obj.Name);
Console.WriteLine("Age: " + obj.Age);
}
}
输出:
Name: Ankita
Age: 21
说明:在上面的程序中,由于变量被声明为私有,因此DemoEncap类被封装。要访问这些私有变量,我们使用Name和Age访问器,其中包含get和set方法来检索和设置私有字段的值。访问器被定义为公共访问器,以便它们可以在其他类中访问。
封装的优点:
- 数据隐藏:用户不会对类的内部实现有任何了解。用户将看不到该类如何在变量中存储值。他只知道我们正在将值传递给访问器,并且变量已被初始化为该值。
- 更高的灵活性:我们可以根据需要将类的变量设置为只读或只写。如果我们希望将变量设为只读,则只需在代码中使用Get Accessor。如果我们希望将变量设置为只写,则只需要使用Set Accessor。
- 可重用性:封装还提高了可重用性,并且易于随新要求进行更改。
- 测试代码很容易:封装的代码很容易进行单元测试。