索引器

索引

沒(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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容