在许多面向对象程序设计语言中,属性(property)是指对象的特征和状态,具体地说就是指对象的数据成员。程序员可以指定数据成员能否被外界直接访问,如果数据成员被指定为public的,外界就可以用“对象名.公有数据成员名”访问该成员。c#是完全面向对象的语言,c#倡导一种新途径,对数据成员能够更好地封装和保护,同时又向外界提供更有效的访问形式。c#中用来达到这个目标的就是“属性”,而那些数据成员,在c#中称为“字段”或“域”。
属性的定义和使用
属性由两个部分组成:属性头和存储器。存储器分为get访问器和set访问器。声明属性的一般形式为:
修饰符 类型 属性名
{
get //get存取程序
{...}
set //set存取程序
{...}
}
属性的修饰符可以是任何访问控制符,还可以被定义为静态。get和set是一种特定的方法,get用来从对象中读取数据,而set用来向字段写入数据,将外界的数据写入字段时,c#使用value表示输入的数据,value可以说是一个准关键字,例如:
set{aField=value;}
以下是一个简单的例子,演示了属性的基本形式和用法:
上面代码中定义了一个属性studentName,它包含get访问器和set访问器。属性studentName封装了类Student中的字段stuName,字段如果没有加访问控制符,被默认为private,外界不能直接访问它,现在外界可以通过studentName属性自由地存取stuName字段了。using System; using System.Collections.Generic; using System.Text; namespace 属性的用法 { public class Student { private string stuName = "阿会楠"; public string studentName { get { return stuName; } set { stuName = value; } } } class Program { static void Main(string[] args) { Student stu = new Student(); Console.Write(stu.studentName); Console.ReadKey(); } } }
属性的get和set都是可执行的程序语句组合,具有行为的特点;而使用具有get访问器和set访问器的属性时候就像使用字段一样,即可以作为左值接受数据,又可以作为右值输出数据,系统正是按照属性出现在语句中的位置,自动地选择是调用get还是调用set。
属性的读写控制
属性中的get和set可以只用一个,如果只有get而没有set,那么这个属性只可读出,不可写入;如果只有set而没有get,那么这个属性是只写入,不可读出。
在属性中完成更多功能
既然get和set是程序,那当然可以做更多的事情。一个合理的分工是:设计字段是为了便于内部方法使用,而尽量与外界隔绝;设计属性考虑的是方便外界的使用,但是不让外界知道的数据一律不给。
最后给一个例子:
using System;
using System.Collections.Generic;
using System.Text;
namespace demo1
{
public class Disk
{
private float width=2;
private float length=3;
private float height=4;
public float Width
{
get { return this.width; }
set { width = value; }
}
public float Length
{
get { return this.length; }
set { length = value; }
}
public float Height
{
get { return this.height; }
set { height = value; }
}
public float GetAll
{
get { return width * length * height; }
}
}
class Program
{
static void Main(string[] args)
{
Disk d1 = new Disk();
d1.Width = 3;
Console.Write(d1.GetAll);
Console.ReadKey();
}
}
}
输出:36