注意:属性本身,没有任何存储
而字段是有存储的。
(1).Set访问器(属性单值)
类的属性
private int old;
public int Old
{
get { return old; }
set {
if (value > 0 && value < 100)
old = value;
else
old = 0;
}
}
调用输出属性
Person a = new Person();
Person b = new Person();
a.Old = 1000;
Console.WriteLine(a.Old);
b.Old = 50;
Console.WriteLine(b.Old);
Console.ReadLine();
输出结果
(2).Set访问器(属性数组)
类的属性
private int[] oldarray = new int[10];
public int[] OldArray
{
get { return oldarray; }
set
{
int count = 0;
foreach (var item in value)
{
if (item > 0 && item < 100)
oldarray[count] = item;
else
oldarray[count] = 0;
count++;
}
}
}
调用输出属性
a.OldArray =new int[10]{-30,20,60,80,131,11,-2,3,-7,60};
Console.WriteLine("输出属性数组");
foreach (var item in a.OldArray)
{
Console.WriteLine(item);
}
Console.ReadLine();
输出结果
(3).Get访问器(属性单值)
类的属性
readonly private string personinfo ="我家在湖北";
public string PersonInfo
{
get
{
return personinfo;
}
}
调用输出属性
Person a = new Person();
Console.WriteLine(a.PersonInfo);
Console.ReadLine();
输出结果
(4).Get访问器(属性数组)
类的属性
readonly private string []personaddress =new string[10] { "湖北", "湖南", "福建", "四川", "广东", "北京", "黑龙江", "江西", "广西", "上海" };
public string[] PersonAddress
{
get
{
return personaddress;
}
}
调用输出属性
Person a = new Person();
foreach (var item in a.PersonAddress)
{
Console.WriteLine(item);
}
Console.ReadLine();
输出结果