1 本我 4小时前 36次点击
索引符(indexer)是一种特殊类型的属性,可以把它添加到一个类中,以提供类似于数组的访问。实际上,可通过索引符提供更复杂的访问,因为我们可以用方括号语法定义和使用复杂的参数类型。它最常见的一个用法是对项实现简单的数字索引。
在Animal对象的Animals集合中添加一个索引符,如下所示:
public class Animals : CollectionBase
{
...
public Animal this[int animalIndex]
{
get { return (Animal)List[animalIndex]; }
Set { List[animalIndex] = value; }
}
}
this关键字需要与方括号中的参数一起使用,除此以外,索引符与其他属性十分类似。这个语法是合理的,因为在访问索引符时,将使用对象名,后跟放在方括号中的索引参数(例如MyAnimals[0])。
这段代码对List属性使用一个索引符(即在IList接口上,可以访问CollectionBase中的ArrayList, ArrayList存储了项):
return (Animal)List[animalIndex];
这里需要进行显式数据类型转换,因为IList.List属性返回一个System.Object对象。注意,我们为这个索引符定义了一个类型。使用该索引符访问某项时,就可以得到这个类型。这种强类型化功能意味着,可以编写下述代码:
animalCollection[0].Feed();
而不是:
((Animal)animalCollection[0]).Feed();
这是强类型化的定制集合的另一个方便特性。下面扩展上一个示例,实践一下该特性。
1新建一个控制台应用程序
2在解决方案资源管理器找练习2,右键弹上下文菜单找添加,选中现有项
3添加练习1的Animal.cs和Cow.cs和Chicken.cs
4修改这3个文件中的名称空间声明,如下所示:
namespace 练习2
5添加一个新类Animals.cs
在Animal.cs添加
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 练习2
{
public class Animals:CollectionBase
{
public void Add(Animal newAnimal)
{
List.Add(newAnimal);
}
public void Remove(Animal newAnimal)
{
List.Remove(newAnimal);
}
public Animal this[int animalIndex]
{
get { return (Animal)List[animalIndex]; }
set { List[animalIndex] = value; }
}
}
}
6在Program.cs添加
using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 练习2
{
class Program
{
static void Main(string[] args)
{
Animals 动物 = new Animals();
动物.Add(new Cow("一号"));
动物.Add(new Chicken("二号"));
foreach (Animal myAnimal in 动物)
{
myAnimal.Feed();
}
ReadKey();
}
}
}