Property的应用说明补充:
一.自定义逻辑:
可以在 get 和 set 访问器中包含自定义的逻辑。
public class Person
{
private string name;
public string Name
{
get { return name; }
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("Name cannot be empty.");
name = value;
}
}
}复制
二.计算属性:
属性也可以是计算的,不依赖于字段。
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public int Area
{
get { return Width * Height; }
}
}复制
三.访问器(Accessors):
属性(Property)的访问器(accessor)包含有助于获取(读取或计算)或设置(写入)属性的可执行语句。访问器(accessor)声明可包含一个 get 访问器、一个 set 访问器,或者同时包含二者。
// 声明类型为 string 的 Code 属性
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// 声明类型为 string 的 Name 属性
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
// 声明类型为 int 的 Age 属性
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
四. 实例:
4.1实例界面
4.2实例代码
class Student { private string code = "N/A"; private string name = "not known"; private int age = 0; // 声明类型为 string 的 Code 属性 public string Code { get { return code; } set { code = value; } } // 声明类型为 string 的 Name 属性 public string Name { get { return name; } set { name = value; } } // 声明类型为 int 的 Age 属性 public int Age { get { return age; } set { age = value; } } public override string ToString() { return "Code = " + Code + ", Name = " + Name + ", Age = " + Age; } } private void test4() { // 创建一个新的 Student 对象 Student s = new Student(); // 设置 student 的 code、name 和 age s.Code = "0001"; s.Name = "Jack"; s.Age = 18; textBox4.Text = "Student Info: " + s.ToString(); // 增加年龄 s.Age += 1; textBox5.Text = "Student Info: " + s.ToString(); } private void button14_Click(object sender, EventArgs e) { test4(); }
复制
以上,一个简单的实例介绍应用,便于理解Property。