索引器
沒(méi)有名字 ,索引器的內(nèi)部本質(zhì)(ILSpy的IL模式下看)類(lèi)型this[參數(shù)]{get;set;}
可以是只讀或者只寫(xiě)(在get或者set前加上private)
字符串是只讀索引,因此不能對(duì)字符串中的某個(gè)字符進(jìn)行從新賦值,即只能char ch = s[5];不能s[5]=‘a(chǎn)’。
開(kāi)發(fā)中自己寫(xiě)的機(jī)會(huì)很少,一道面試題:C#中索引器是否只能根據(jù)數(shù)字進(jìn)行索引?是否允許多個(gè)索引器參數(shù)?答案:可以進(jìn)行非數(shù)字索引,可以允許多個(gè)參數(shù)進(jìn)行索引
using System;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceTestConsole
{
???class Program
???{
??????? static void Main(string[] args)
??????? {
??????????? MyIntIndex myIntIndex = newTestConsole.MyIntIndex();//整型索引
??????????? stringname1 = myIntIndex[1];
??????????? Console.WriteLine(name1);
??????????? Hashtable ht = new Hashtable();
??????????? ht.Add("001", "chizi");
??????????? ht.Add("002", "dandan");
??????????? MyStringIndex myStringIndex = newTestConsole.MyStringIndex(ht);//字符串索引
??????????? string name2 = myStringIndex["001"];
??????????? Console.WriteLine(name2);
??????? ????Console.ReadKey();
??????? }
???}
???class MyStringIndex
???{
??????? private Hashtable ht;//字符串索引用到哈希表來(lái)存放鍵值對(duì)
??????? public MyStringIndex(Hashtableht)
??????? {
??????????? this.ht = ht;
??????? }
??????? public string this[stringkey]
??????? {
??????????? get
??????????? {
??????????????? string name =(string)ht[key];
??????????????? returnname;
??????????? }
??????????? set
??????????? {
??????????????? ht[key] =value;
??????????? }
??????? }
???}
???class MyIntIndex
???{
??????? private static string[] name = { "dandan", "chizi", "jianguo"};
??????? public string this[intindex]
??????? {
??????????? get
??????????? {
??????????????? stringn = name[index];
??????????????? returnn;
??????????? }
??????????? set
??????????? {
?????????? ?????name[index] =value;
??????????? }
??????? }
???}
}???N%k1}?? ???[??89