c#初学-索引器get和set的使用(泛型类)

索引器允许类或结构的实例就像数组一样进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。

在下面的示例中,定义了一个泛型类,并为其提供了简单的 getset 访问器方法(作为分配和检索值的方法)。Program 类为存储字符串创建了此类的一个实例。

class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}

// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
 
      
  • 使用索引器可以用类似于数组的方式为对象建立索引。

  • get 访问器返回值。set 访问器分配值。

  • this 关键字用于定义索引器。

  • value 关键字用于定义由 set 索引器分配的值。

  • 索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。

  • 索引器可被重载。

  • 索引器可以有多个形参,例如当访问二维数组时。

this,类的索引器:

    下面的示例说明如何声明私有数组字段、temps 和索引器。使用索引器可直接访问实例 tempRecord[i]。另一种使用索引器的方法是将数组声明为 public 成员并直接访问它的成员 tempRecord.temps[i]

请注意,当计算索引器的访问时(例如,在 Console.Write 语句中),将调用 get 访问器。因此,如果 get 访问器不存在,将发生编译时错误。

代码

class TempRecord
{
// Array of temperature values
private float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F,
61.3F, 65.9F, 62.1F, 59.2F, 57.5F };

// To enable client code to validate input
// when accessing your indexer.
public int Length
{
get { return temps.Length; }
}
// Indexer declaration.
// If index is out of range, the temps array will throw the exception.
public float this[int index]
{
get
{
return temps[index];
}

set
{
temps[index] = value;
}
}
}

class MainClass
{
static void Main()
{
TempRecord tempRecord = new TempRecord();
// Use the indexer's set accessor
tempRecord[3] = 58.3F;
tempRecord[5] = 60.1F;

// Use the indexer's get accessor
for (int i = 0; i < 10; i++)
{
System.Console.WriteLine("Element #{0} = {1}", i, tempRecord[i]);
}

// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();

}
}

C# 并不将索引类型限制为整数。例如,对索引器使用字符串可能是有用的。通过搜索集合内的字符串并返回相应的值,可以实现此类索引器。由于访问器可被重载,字符串和整数版本可以共存。

说明

在此例中,声明了存储星期几的类。声明了一个 get 访问器,它接受字符串(天名称),并返回相应的整数。例如,星期日将返回 0,星期一将返回 1,等等。

代码

// Using a string as an indexer value
class DayCollection
{
string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };

// This method finds the day or returns -1
private int GetDay(string testDay)
{

for(int j = 0; j < days.Length - 1; j++)
{
if (days[j] == testDay)
{
return j;
}
}

throw new System.ArgumentOutOfRangeException(testDay, "testDay must be in the form \"Sun\", \"Mon\", etc");
}

// The get accessor returns an integer for a given string
public int this[string day]
{
get
{
return (GetDay(day));
}
}
}

class Program
{
static void Main(string[] args)
{
DayCollection week = new DayCollection();
System.Console.WriteLine(week["Fri"]);

// Raises ArgumentOutOfRangeException
System.Console.WriteLine(week["Made-up Day"]);

// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
// Output: 5

提高索引器的安全性和可靠性有两种主要的方法:

  • 确保结合某一类型的错误处理策略,以处理万一客户端代码传入无效索引值的情况。在本主题前面的第一个示例中,TempRecord 类提供了 Length 属性,使客户端代码能够在将输入传递给索引器之前对其进行验证。也可以将错误处理代码放入索引器自身内部。确保为用户记录在索引器的访问器中引发的任何异常。有关更多信息,请参见异常设计准则

  • 应当为 getset 访问器的可访问性设置尽可能多的限制。这一点对 set 访问器尤为重要。有关更多信息,请参见 非对称访问器可访问性(C# 编程指南)

属性和索引器之间的比较:

索引器与属性类似。除下表中显示的差别外,为属性访问器定义的所有规则同样适用于索引器访问器。

 

属性

索引器

允许像调用公共数据成员一样调用方法。

允许对一个对象本身使用数组表示法来访问该对象内部集合中的元素。

可通过简单的名称进行访问。

可通过索引器进行访问。

可以为静态成员或实例成员。

必须为实例成员。

属性的 get 访问器没有参数。

索引器的 get 访问器具有与索引器相同的形参表。

属性的 set 访问器包含隐式 value 参数。

除了参数外,索引器的 set 访问器还具有与索引器相同的形参表。

支持对自动实现的属性(C# 编程指南)使用短语法。

不支持短语法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值