C# .NET 索引器的基本使用

索引器和属性差不多,属性是一对一,而索引器是一对多而已。

(一) int 索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
mc[0] = "胡文杰";
mc[1] = "杨佳";
Console.WriteLine(mc[0]);
Console.WriteLine(mc[1]);

Console.Read();
}
}

class MyClass
{
private string[] name = new string[2];
// 关键:用 this 代替,类型也可以用 string
public string this[int index] {
get {
if (index >= 0 && index < name.Length) {
return name[index];
}
else {
return name[0];
}
}
set {
if (index >=0 && index < name.Length) {
name[index] = value;
}
}
}
}

输出:

1
2
胡文杰
杨佳

string 索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;


namespace RefTest
{
class Employee
{
public string name;
public string Age;
public string Gender;

public Employee(string n, string a, string g)
{
name = n;
Age = a;
Gender = g;
}

public string this[string str] {
set {
switch (str) {
case "姓名":
name = value;
break;
case "年龄":
Age = value;
break;
case "性别":
Gender = value;
break;
//default:
//throw new Exception().Message;
}
}
get {
switch (str) {
case "姓名": return name;
case "年龄": return Age;
case "性别": return Gender;

default:
throw new ArgumentOutOfRangeException("index");
}
}
}


class Program
{

static void Main()
{
Employee employee = new Employee("周杰伦", "12", "男");

Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]);

Console.WriteLine("\n改名:");

employee["姓名"] = "猪八戒";

Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]);

Console.ReadKey();
}
}
}
}

输出:

1
2
3
4
周杰伦 12 男

改名:
猪八戒 12 男
感谢支持!