索引器是一种允许使用方括号 [] 访问对象的特定属性的语法特性。它本质上是一个具有特殊语法和语义的对象属性。
[index] { get; [set; ] }
其中:
index
是一个可以是任何类型(例如整数、字符串或对象)的表达式。
get
是一个用于获取索引器值的可选访问器方法。
set
是一个用于设置索引器值的可选访问器方法。
class MyIndexedClass
{private int[] _data;public int this[int index]{get { return _data[index]; }set { _data[index] =value; }}
}
您可以使用以下代码访问和设置索引器:
MyIndexedClass myIndexedClass = new MyIndexedClass(); myIndexedClass[0] = 10; int value = myIndexedClass[0];
public int this[int index] { get; }
public int this[int index] { set; }
static
,这意味着它可以从类的任何位置访问,而无需创建实例:
public static int this[int index] { get; set; }
public T this[TKey index] { get; set; }
static 静态 加了static保存的变量可以随时引用,在整个项目中最好少用,太耗内存 而且调用时不用实例化非静态 每次调用还要实例化重新分配内存,他里面的值只能本类中调用
实例+索引的方法来访问类成员。 using System;class MyTest{public static int Main(){schoolMate myMate=new SchoolMate();([0]); //直接访问成员 //以索引器的形式访问成员(name:{0},myMate[0]); (Enter your name:);myMate[0]=();(name:{0},myMate[0]);(sex:{0},myMate[1]);(age:{0},myMate[2]);return 0;}}class SchoolMate{public string[] linkman; public SchoolMate(){linkman=new string[]{yesline,male,23};} public string this[int index]//string指返回值,this指类,或此类创建的实例。 {get{return linkman[index];}set{linkman[index]=value;}} }在此成员中,访问linkman数组当然可以用另外的方法,如访问第一个成员[0]。 既然可以这样,为什么要用索引器呢?书上说当类是容器时用索引器有用,可我还没看到此类例子。 可以重载索引器。 如再定义一个索引器:public int othertest=23;//定义public int this[string index] //index的类型不能在为int,因为已定义过{get{return othertest;}set{othertest=value;}}//使用,查看结果(myMate[1]);//myMate[]中所以可以为任意string//输出:23麻烦采纳,谢谢!
在本示例中,定义了一个泛型类,并为其提供了简单的get和set访问器方法(作为分配和检索值的方法)。 Program 类为存储字符串创建了此类的一个实例。 代码如下:class SampleCollection{ private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } 下面是如何使用上述代码实现的索引器,具体代码示例如下: class Program { static void Main(string[] args) { SampleCollection s = new SampleCollection(); s[0] = 索引器的使用; (s[0]); } } C#并不将索引类型限制为整数。 例如,对索引器使用字符串可能是有用的。 通过搜索集合内的字符串并返回相应的值,可以实现此类的索引器。 如下所示: using System; using ; class IndexClass { private Hashtable ht = new Hashtable(); public object this[object key] { get { return ht[key]; } set { ht[key] = value; } } } 由于访问器可被重载,字符串和整数版本可以共存。 以上代码中的关键字value用来定义设置索引器分配的值,关键字this用于定义的索引器。
本文地址:https://www.badfl.com/article/89e50c508dcbd49cd47d.html