using System.Collections;
internal class Program
{
static void Main(string[] args)
{
GroupDogShell groupDogShell = new GroupDogShell(new GroupDog( new List<Dog>(){ new Dog("大黄"), new Dog("小黑") } ), new List<string>() { "健康", "活力四射" });
var ii = groupDogShell[1];
foreach (var item in groupDogShell)
{
Console.Write(item[1] as string); (item[0] as Dog).Bark();
}
}
}
public class Dog
{
private string name;
public Dog(string name) { this.name = name; }
public void Bark()
{Console.WriteLine(name + ":汪汪");}
}
public class GroupDog
{
private List<Dog> list;
public int Count{get{return list.Count;}}
public GroupDog(List<Dog> list)
{
this.list = list;
}
public Dog this[int i]
{
get { return list[i]; }
set { list[i] = value; }
}
}
public class GroupDogShell : IEnumerable<List<object>>
{
private GroupDog dogGroup;
private List<string> HealthList;
public GroupDogShell(GroupDog group, List<string> listAdded)
{
this.dogGroup = group;
this.HealthList = listAdded;
}
public List<object> this[int i]
{
get { return new List<object>() { dogGroup[i], HealthList[i] }; }
set { dogGroup[i] = (Dog)value[0]; HealthList[i] = (string)value[1]; }
}
public IEnumerator<List<object>> GetEnumerator()//实现接口
{
for (int i = 0; i < dogGroup.Count; i++)//使用其中一个索引来迭代
{
yield return new List<object>() { dogGroup[i], HealthList[i] };
}
}
IEnumerator IEnumerable.GetEnumerator()//实现接口
{
return GetEnumerator();
}
}
自己编的一种所谓的"设计模式". ^o^
一句话: 需要拓展一个带索引器的类的功能, 又不想更改这个类. 即可使用另一个带索引器类, 索引与之一一对应.
Unity渲染系统使用了相似的思想, [UV数组]和[顶点位置数组]的索引一一对应