C#-----属性和索引器
属性介绍:
属性是对成员变量的读写之前进行验证,看条件是否符合,主要针对变量是普通类型的情况
索引器也是完成验证的过程,只不过它主要是针对变量是数组或集合的情况,通过索引器下标找到给数组或集合里面的哪个变量进行赋值或读值。
class Student
{
public int nAge = 1000;
//年龄属性
public int Age
{
get
{
return nAge;
}
set
{
if (value < 100)
{
nAge = value;
}
else
{
Console.WriteLine("年龄不符合要求");
}
}
}
static void Main(string[] args)
{
Student obj = new Student();
int num = obj.nAge;
Console.WriteLine(obj.nAge);
Console.WriteLine(num);
obj.Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(obj.Age);
Console.Read();
}
索引器示例一
class Program
{
/// <summary>
/// 这是一个控制台程序
/// </summary>
private string[] arr;
public string[] aa = new string[3];
public Program()
{
arr = new string [4];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = "张三";
}
}
public string this[int index]
{
get { return arr[index]; }
set { arr[index] = value; }
}
public string this[string str]
{
get
{
int count = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == str)
{
count++;
}
}
return count.ToString();
}
set
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == str)
{
arr[i] = value;
}
}
}
}
static void Main(string[] args)
{
Program pr = new Program();
//写入部分值
pr[0] = "wangwu";
pr[2] = "liuba";
for (int i = 0; i <pr.arr.Length; i++)
{
Console.WriteLine(pr[i]);
}
//读取值
pr["张三"] = "张三都被替换了";
for (int i = 0; i < pr.arr.Length; i++)
{
Console.WriteLine(pr[i]);
}
Console.WriteLine(pr["张三"]);
Console.Read();
}
}