介面中的索引器(C# 編程指南)

來源:互聯網
上載者:User

 

介面中的索引器(C# 編程指南) 索引器可在介面(C# 參考)上聲明。介面索引器的訪問器與類索引器的訪問器具有以下方面的不同:介面訪問器不使用修飾符。介面訪問器沒有體。因此,訪問器的用途是指示索引器是讀寫、唯讀還是唯寫。以下是介面索引器訪問器的樣本:C#複製代碼public interface ISomeInterface{    //...     // Indexer declaration:    stringthis[int index]    {        get;        set;    }}一個索引器的簽名必須區別於在同一介面中聲明的其他所有索引器的簽名。 樣本 下面的樣本顯示如何?介面索引器。C#複製代碼// Indexer on an interface:public interface ISomeInterface{    // Indexer declaration:    intthis[int index]    {        get;        set;    }} // Implementing the interface.class IndexerClass : ISomeInterface{    privateint[] arr = newint[100];    publicintthis[int index]   // indexer declaration    {        get        {            // Check the index limits.            if (index < 0 || index >= 100)            {                return 0;            }            else            {                return arr[index];            }        }        set        {            if (!(index < 0 || index >= 100))            {                arr[index] = value;            }        }    }} class MainClass{    staticvoid Main()    {        IndexerClass test = new IndexerClass();        // Call the indexer to initialize the elements #2 and #5.        test[2] = 4;        test[5] = 32;        for (int i = 0; i <= 10; i++)        {            System.Console.WriteLine("Element #{0} = {1}", i, test[i]);        }    }} 輸出 Element #0 = 0Element #1 = 0Element #2 = 4Element #3 = 0Element #4 = 0Element #5 = 32Element #6 = 0Element #7 = 0Element #8 = 0Element #9 = 0Element #10 = 0在上例中,可以通過使用介面成員的完全限定名來使用顯式介面成員實現。例如:public string ISomeInterface.this { } 但是,只有當類使用同一索引器簽名實現一個以上的介面時,為避免多義性才需要使用完全限定名。例如,如果 Employee類實現的是兩個介面 ICitizen和 IEmployee,並且這兩個介面具有相同的索引器簽名,則必須使用顯式介面成員實現。即,以下索引器聲明:public string IEmployee.this { } 在 IEmployee介面上實現索引器,而以下聲明:public string ICitizen.this { } 在 ICitizen介面上實現索引器。  (來源:msdn ) 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.