C#类索引器的使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#类索引器的使用相关的知识,希望对你有一定的参考价值。
索引器提供了一种可以让类被当作数组进行访问的方式。在C#中,类索引器是通过this的属性实现的。
index.ToString("D2")将index转换成一个具有两个字符宽度的字符串
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassIndexer { /// <summary> /// define a class called AClass,which has only one private variable /// </summary> class AClass { private string _name; public string Name { get { return this._name; } set { this._name = value; } } public AClass(string name) { this._name = name; } } /// <summary> /// AClassContainer class /// </summary> class AClassContainer { private AClass[] _AClassList; public AClassContainer() { this._AClassList = new AClass[10]; } public AClassContainer(int cap) { this._AClassList = new AClass[cap]; } /// <summary> /// class indexer by using int /// </summary> /// <param name="index"></param> /// <returns></returns> public AClass this[int index] { get { if ((index < 0) || (index > this._AClassList.Length)) return null; else return this._AClassList[index]; } set { if ((index < 0) || (index > this._AClassList.Length)) return; else this._AClassList[index] = value; } } /// <summary> /// class indexer by using string /// </summary> /// <param name="name"></param> /// <returns></returns> public AClass this[string name] { get { foreach (AClass cls in this._AClassList) { if (cls.Name == name) return cls; } return null; } } } class Program { static void Main(string[] args) { int count = 10; AClassContainer classContainer = new AClassContainer(count); for (int index = 0; index < count; index++) { string name = index.ToString("D2"); classContainer[index] = new AClass(name); } for (int index = 0; index < count; index++) { AClass cls = classContainer[index]; System.Console.WriteLine("classContainer[{0}].Name=\"{1}\"",index,cls.Name); } System.Console.WriteLine(); for (int index = count - 1; index >= 0; index--) { string name = index.ToString("D2"); AClass cls = classContainer[name]; System.Console.WriteLine("classContainer[{0}].Name=\"{1}\"",name,cls.Name); } System.Console.ReadLine(); } } } 结果: classContainer[0].Name="00" classContainer[1].Name="01" classContainer[2].Name="02" classContainer[3].Name="03" classContainer[4].Name="04" classContainer[5].Name="05" classContainer[6].Name="06" classContainer[7].Name="07" classContainer[8].Name="08" classContainer[9].Name="09" classContainer[09].Name="09" classContainer[08].Name="08" classContainer[07].Name="07" classContainer[06].Name="06" classContainer[05].Name="05" classContainer[04].Name="04" classContainer[03].Name="03" classContainer[02].Name="02" classContainer[01].Name="01" classContainer[00].Name="00"
以上是关于C#类索引器的使用的主要内容,如果未能解决你的问题,请参考以下文章