C# 索引器方法
使用索引操作 [] 訪問包含在一個標準數組中的各個子項。
定義:把能使用索引操作符 [] 訪問子項的方法稱為索引器方法
1、自定義索引器方法(this):
public class PeopleCollection : IEnumerable {private ArrayList arPeople= new ArrayList();// 類的自定義索引器public Person this [int index] // 除了多個this關鍵字外,和屬性聲明很相似 {get{ return (Person)arPeople[index];}set{ arPeople.Insert(index,value);} // 使用ArrayList的Insert()方法 } }2、泛型類型直接支持索引器方法:
List<Person> myPeople=new List<Person>(); myPeople.Add(new Person {"lisa","simpson",19}); myPeople.Add(new Person {"lilei","simpson",20}); // 使用索引器修改第一個值 myPeople[0]=new Person {"zhangsan","simpson",20} ; ...3、使用字符串值索引對象
如果直接使用泛型?Dictionary<TKey,TValue>類型,可以直接獲得索引器方法功能,而不用自己去構建
public class PeopleCollection : IEnumerable {private Dictionary<string,Person> listPeople= new Dictionary<string,Person>();// 基于一個字符串索引返回一個Personpublic Person this [string name] {get{ return (Person)listPeople[name];}set{ listPeople[name]=value;} }... }4、重載索引器方法
索引器方法可以在單個類或結構上被重載。
//DataTableCollection類型,重載的索引器 public DataTable this[string name] {get;} public DataTable this[string name,string tableNamespace]{get;} public DataTable this[int index]{get;}5、多維索引器:典型代表是ADO.NET中的 DataTable
private int[,] myArray = new int[10,10];public int this[int row ,int colum] {/* 從二位數組中取值或賦值*/}6、接口類型上定義索引器
在接口定義索引器,其實現類就可以提供自定義實現
public interface IStringContainer {//該接口定義了一個索引器,該索引器基于數字索引返回字符串string this[int index] {get;set;} }?
轉載于:https://www.cnblogs.com/senyier/p/6617424.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: nginx端合并JS
- 下一篇: iOS 商城类 app 首页的实现