您的位置:首页 > 编程语言 > C#

C#学习笔记9-属性

2010-04-01 08:55 211 查看
属性提供灵活的机制来读取、编写、计算私有的字段。可以像使用公共数据成员一样来使用属性,他们是称作“访问器”的特殊方法,这样就可以轻松你的访问数据。

属性使类以一种公开的方法访问和设置值。get属性访问用户返回属性值,get必须以return或throw作为终止;set属性访问器用于分配新值,而value关键字用于设置为属性分配的新值。不具有set访问器的属性被认为具有只读属性。

实例1:实例、静态和只读属性

public class Employee
{
public static int numberOfEmployees;
public static int counter;
private string name;

public string Name//read-write property
{
get { return name; }
set { name = value; }
}
public static int Counter//read-only
{
get { return counter; }
}
public Employee()//constructor
{
counter = ++counter + numberOfEmployees;
}
}

class TesEmployee
{
static void Main()
{
Employee.numberOfEmployees = 222;
Employee e1 = new Employee();
e1.Name = "myname";//name不可访问,但是属性Name是可读可写的
Console.WriteLine("Employee number:{0}", Employee.Counter);//Counter是静态的,不能实例化调用
Console.WriteLine("Employee name:{0}", e1.Name);
Console.ReadKey();
}
}


示例2

abstract class Shape
{
public abstract double Area
{
get;
set;
}
}
class Square : Shape
{
private double side;
public Square(double s)//constructor
{
side = s;
}
public override double Area
{
get
{
return side * side;
}
set
{
side = value;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: