using System;
using System.Collections.Generic;
using System.Text;
namespace property
{
class PropertyTest
{
private int age;//声明属性
public PropertyTest(int age) {//构造方法
this.age = age;
}
//传统的访问类的成员变量写法
//public int getAge() {
// return this.age;
//}
//public void setAge(int age) {
// if (age > 0 && age <= 100) {
// this.age = age;
// }
//}
//不直接操作类的数据内容,通过访问器进行访问,借助于set和get对属性进行读写
public int Age {//定义一个可以读写的属性,注意属性名要大写
get {
return this.age;
}
set {
if (value > 0 && value <= 100)//value用于定义有set索引器分配的值,可以理解为一个隐含的参数
{
this.age = value;
}
}
}
}
class ReadProperty {
private string name;
public ReadProperty(string name) {
this.name = name;
}
public string Name {//只读属性
get {
return this.name;//返回属性值
}
}
}
class Test {
static void Main(string[] args) {
PropertyTest pt = new PropertyTest(33);
pt.Age = 12;//修改属性值
Console.WriteLine("年龄为:"+pt.Age);
ReadProperty rt = new ReadProperty("张三");
// rt.Name = "王五";//出错,因为是只读的属性,不能修改
Console.WriteLine("姓名为:" + rt.Name);
Console.Read();
}
}
}