一、索引器(Indexer)允許類和結構的實體像陣列一樣通過索引取值,可以看做是對[]運算子的多載,索引器實際上就是有引數的屬性,也被稱為有參屬性或索引化屬性,其宣告形式與屬性相似,不同之處在于索引器的訪問器需要傳入引數;
1.宣告索引器:
class MyClass { string[] myArray = new string[100]; public string this[int index] //使用關鍵字this定義索引器 { get { return myArray[index]; } set { myArray[index] = value; } } } //使用索引器: MyClass myClass = new MyClass(); myClass[0] = "1"; Console.WriteLine(myClass[0]); //1
※屬性和索引器都不被當作變數,二者都是在基于方法實作的,因此無法將屬性或索引器作為參考引數、參考回傳值、參考區域變數來傳遞和使用;
※索引器只能宣告為實體成員,不能宣告為靜態的;
※索引器不支持自動實作;
※索引器只是在呼叫的寫法上與陣列相同,但實作原理與陣列完全不同,二者不可混淆;
2.宣告泛型版本的索引器:
class MyClass<T> { private T[] myArray = new T[100]; public T this[int index] { get { return myArray[index]; } set { myArray[index] = value; } } } //使用索引器: MyClass<string> myClass = new MyClass<string>(); myClass[0] = "1"; Console.WriteLine(myClass[0]); //1
3.索引器不僅可以根據整數進行索引,還可以根據任何型別進行索引,同時索引器也支持多載,類似于方法的多載,需要引數串列不完全相同,例如:
public int this[string content] { get { return Array.IndexOf(myArray, content); } }
4.索引器同時也支持引數串列有多個引數,類似于使用多維陣列,例如:
string[,] myArray = new string[100, 100]; public string this[int posX, int posY] { get { return myArray[posX, posY]; } set { myArray[posX, posY] = value; } } //使用索引器: MyClass myClass = new MyClass(); myClass[0, 0] = "1"; Console.WriteLine(myClass[0, 0]); //1
二、索引器實際上就是有引數的屬性,其屬性名固定為Item,通過反射獲取MyClass的屬性資訊陣列即可看到:
Type myType = typeof(MyClass); PropertyInfo[] myProperties = myType.GetProperties(); for (int i = 0; i < myProperties.Length; i++) { Console.WriteLine(myProperties[i].Name); //Item }
1.通過反射呼叫索引器獲取值:
MyClass myClass = new MyClass(); for (int i = 0; i < 100; i++) { myClass[i] = i.ToString(); } PropertyInfo data = myType.GetProperty("Item"); //如果索引器包含多載,例如上面this[string content]的例子,那么使用GetProperty的多載方法傳入引數串列的型別陣列來獲取指定索引器myType.GetProperty("Item", new Type[] { typeof(int) }) string myStr = (string)data.GetValue(myClass, new object[] { 5 }); //第二個引數即索引器引數 Console.WriteLine(myStr); //5
2.查看其IL代碼:


如果您覺得閱讀本文對您有幫助,請點一下“推薦”按鈕,您的認可是我寫作的最大動力!
作者:Minotauros
出處:https://www.cnblogs.com/minotauros/
本文著作權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/56675.html
標籤:C#
上一篇:使用物件初始值設定項初始化
下一篇:String.Split分隔字串
