属性(Property) 是类(class)、结构(structure)和接口(interface)的命名(named)成员。类或结构中的成员变量或方法称为 域(Field)。属性(Property)是域(Field)的扩展,且可使用相同的语法来访问。它们使用 访问器(accessors) 让私有域的值可被读写或操作。
using System;
namespace Accessors
{
class Student
{
//private Field
private string name = "";
private string sex = "";
private int age = 0;
public string Sex //sex accessor
{
get
{
return sex;
}
set
{
sex = value;
}
}
public string Name //name accessor
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age //age accessor
{
get
{
return age;
}
set
{
age = value;
}
}
public override string ToString()
{
return "Name = " + Name +", Sex = " + Sex + ", Age = " + Age;
}
}
// class Student
// {
// //property
// public string Sex {get;set;}
// public string Name {get;set;}
// public int Age {get;set;}
//
// public override string ToString()
// {
// return "Name = " + Name +", Sex = " + Sex + ", Age = " + Age;
// }
// }
class Program
{
public static void Main(string[] args)
{
Student sObj = new Student();
sObj.Name = "zhangsan";
sObj.Sex = "man";
sObj.Age = 31;
Console.WriteLine(sObj);
Console.ReadKey(true);
}
}
}
上面代码中,前面的student类中有私有成员,外部访问通过索引器访问,对私有变量进行set或get操作
后面的student类可以不用这些私有成员,它们都是有get和set方法的属性,直接对这些属性操作即可。