封装的意义在于保护或者防止代码(数据)被我们无意中破坏。有的数据可以用两种方式来间接的控制。下面我们看一些c#例子来学习这两种方法用以封装数据。第一种方法,我们使用传统的存、取方法。第二种方法我们用属性(property)。无论我们使用哪种的方法,我们的目标是在使用数据的同时不能使它受到任何的破坏和改变。
只写属性
using system;
public class Department
{
private string departname;
.......
// 读方法
public string GetDepartname()
{
return departname;
}
//写方法
public void SetDepartname( string a)
{
departname=a;
}
}
public static int Main(string[] args)
{
Department d = new Department();
d.SetDepartname("ELECTRONICS");
Console.WriteLine("The Department is :"+d.GetDepartname());
return 0;
}
用属性来实现封装
using system;
public class Department
{
private string departname;
public string Departname
{
get
{
return departname;
}
set
{
departname=value;
}
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d= new Department();
d.departname="Communication";
Console.WriteLine("The Department is :{0}",d.Departname);
return 0;
}
}
只读属性
using system;
public class ReadDepartment
{
private string departname;
public ReadDepartment(string avalue)
{
departname=avalue;
}
public string Departname
{
get
{
return departname;
}
}
}
public class ReadDepartmain
{
public static int Main(string[] args)
{
ReadDepartment d= new ReadDepartment("COMPUTERSCIENCE");
Console.WriteLine("The Department is: {0}",d.Departname);
return 0;
}
}
只写属性
using system;
public class WriteDepartment
{
private string departname;
public string Departname
{
set
{
departname=value;
Console.WriteLine("The Department is :{0}",departname);
}
}
}
public class WriteDepartmain
{
public static int Main(string[] args)
{
WriteDepartment d= new WriteDepartment();
d.departname="COMPUTERSCIENCE";
return 0;
}
}