C#索引器
▢ 索引器提供了一种可以访问封装了列表值或字典的class/struct的元素的一种自然的语法
string s="hello";
Console.WriteLine(s[0]); // 'h'
Console.WriteLine(s[3]); // 'l'
▢ 语法很像使用数组时用的语法,但是这里的索引参数可以是任何类型的
▢ 索引器和属性拥有同样的修饰符
▢ 可以按照下列方式使用null条件操作符
string s=null;
Console.WriteLine(s?[0]);
▢ 实现索引器需要定义this属性,并通过中括号指定参数
举例:
namespace 实现索引器
{
class Sentence
{
string[] words = "This is China".Split();public string this[int wordNum]
{
get { return words[wordNum]; }
set { words[wordNum] = value; }
}
}
class Program
{
static void Main(string[] args)
{
Sentence s = new Sentence();
Console.WriteLine(s[2]); //China
Console.Read();
}
}
}
输出:
China
▢ 一个类型可以声明多个索引器,它们的参数类型可以不同
▢ 一个索引器可以有多个参数
比如:
public string this [int arg1,string arg2]
{
get{...} set{...}
}
▢ 如果不写set访问器,那么这个索引器就是只读的
▢ 在C#6以后,也可以使用 expression-bodied 语法
public string this [int wordNum]=>words[wordNum];
Tips:
索引器在内部会编译成get_Item和set_Item方法
public string get_Item(int wordNum){...}
public void set_Item(int wordNum,string value){...}
Today's comments have reached the limit. If you want to comment, please wait until tomorrow (UTC-Time).
There is 04h28m37s left until you can comment.