今天突然被人问到,C#中什么是索引器?
脑子一片空白, 那个啥就是一个方括号。 懵逼的回答。
先百科一下,得到如下结果:
C# 索引器(Indexer)
索引器(Indexer) 允许一个对象可以像数组一样使用下标的方式来访问。
当您为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。您可以使用数组访问运算符 [ ] 来访问该类的的成员。
然后自己定义一个泛型索引器的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication_IndentityServerCeint_Test
{
public class GenericIdenx<T>
{
List<T> ls = new List<T>();
public T this[int id] {
get { return ls[id]; }
set { ls[id] = value; }
}
}
}
感觉也没啥,关键字 this是C#中的默认索引器, 当然你自己可也以去定义一个索引器。
但是秉着有现成不用就是,蛋蛋。
就行.net内置 泛型委托Action 和Func . 嗯还是内置的香。
嗯完结。