利用索引器取值 赋值
案例1
c#// 创建Test.cs 类
class Test {
public string this[int index] {
get {
Console.WriteLine([index]);
return 100;
}
set {
Console.WriteLine([index]);
Console.WriteLine(value);
}
}
}
c#//使用 Program.cs
Test t = new Test();
t[9] = 200;
Console.WriteLine(t[9]);
案例2
c#// 创建Test.cs 类
class Test {
private string[] name = new string[10];
public string this[int index] {
get {
return name[index];
}
set {
name[index] = value;
}
}
}
c#//使用 Program.cs
Test t = new Test();
t[0] = "张三";
t[1] = "李四"; //赋值
Console.WriteLine(t[0]);
Console.WriteLine(t[1]); //取值
案例3
c#// 创建Week.cs 类
class Week {
private string[] days = {
"Mon",
"Tues",
"Wed",
"Thu",
"Fri",
"Sat",
"Sun"
};
// public int GetDay(string day) //传递英文返回数值
private int GetDay(string day) //使用方法2索引时,需将public改为private
{
int i = 0; //开始传递
foreach(string temp in days) {
if (temp == day) return i + 1; //找到索引
i++;
}
return -1;
}
public int this[string day] {
get {
return GetDay(day); //调用上面的方法
}
}
}
c#//使用 Program.cs
//方法1
Week w = new Week();
Console.WriteLine(w.GetDay("Thu"));
//方法2
Console.WriteLine(w["Sat"]);
本文作者:千纸鹤
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!