索引器和属性(C# 编程指南)
索引器
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
在下面的示例中,定义了一个泛型类,并为其提供了简单的 get 和 set 访问器方法(作为分配和检索值的方法)。Program 类为存储字符串创建了此类的一个实例。
1
class SampleCollection<T>
2
{
3
private T[] arr = new T[100];
4
public T this[int i]
5
{
6
get
7
{
8
return arr[i];
9
}
10
set
11
{
12
arr[i] = value;
13
}
14
}
15
}
16![]()
17
// This class shows how client code uses the indexer
18
class Program
19
{
20
static void Main(string[] args)
21
{
22
SampleCollection<string> stringCollection = new SampleCollection<string>();
23
stringCollection[0] = "Hello, World";
24
System.Console.WriteLine(stringCollection[0]);
25
}
26
}
27![]()
class SampleCollection<T>2
{3
private T[] arr = new T[100];4
public T this[int i]5
{6
get7
{8
return arr[i];9
}10
set11
{12
arr[i] = value;13
}14
}15
}16

17
// This class shows how client code uses the indexer18
class Program19
{20
static void Main(string[] args)21
{22
SampleCollection<string> stringCollection = new SampleCollection<string>();23
stringCollection[0] = "Hello, World";24
System.Console.WriteLine(stringCollection[0]);25
}26
}27

索引器概述
属性
属性是这样的成员:它们提供灵活的机制来读取、编写或计算私有字段的值。可以像使用公共数据成员一样使用属性,但实际上它们是称为“访问器”的特殊方法。这使得数据在可被轻松访问的同时,仍能提供方法的安全性和灵活性。
在本示例中,类 TimePeriod 存储了一个时间段。类内部以秒为单位存储时间,但提供一个称为 Hours 的属性,它允许客户端指定以小时为单位的时间。Hours 属性的访问器执行小时和秒之间的转换。
示例:
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
输出
Time in hours: 24
属性概述
索引器和属性之间的比较
|
属性 |
索引器 |
|---|---|
|
允许调用方法,如同它们是公共数据成员。 |
允许调用对象上的方法,如同对象是一个数组。 |
|
可通过简单的名称进行访问。 |
可通过索引器进行访问。 |
|
可以为静态成员或实例成员。 |
必须为实例成员。 |
|
属性的 get 访问器没有参数。 |
索引器的 get 访问器具有与索引器相同的形参表。 |
|
属性的 set 访问器包含隐式 value 参数。 |
除了 value 参数外,索引器的 set 访问器还具有与索引器相同的形参表。 |


浙公网安备 33010602011771号