2016-07-21 17 views
0

我在索引中聲明瞭兩個私有數組,並在main中顯示數據。但是,它沒有顯示任何一個告訴我如何在索引器中的兩個私有數組中顯示數據?通過在c中使用索引器在私有數組中排列數據#

class Program 
{ 
    static void Main(string[] args) 
    { 

     student sc = new student(); 
     for (int i = 0; i < sc.mlength; i++) 
     { 
      Console.WriteLine(sc[i]); 
     } 
     Console.ReadLine(); 
     //i am declaring two private arrays in indexes and displaying the data in main is not displaying any one tell me how to display the data in the two private arrays in indexers? 
    } 
} 
public class student 
{ 
    private int[] _marks = new int[] { 60, 68, 70 }; 
    private string[] _names = new string[] { "suri", "kumar", "suresh" }; 
    public int this[int i] 
    { 
     get 
     { 
      return _marks[i]; 
     } 
     set 
     { 
      _marks[i] = value; 
     } 

    } 
    public string this[int i] 
    { 
     get 
     { 
      return _names[Convert.ToInt32(i)]; 
     } 
     set 
     { 
      _names[Convert.ToInt32(i)] = value; 
     } 
    } 
    public int mlength 
    { 
     get 
     { 
      return _marks.Length; 
     } 
    } 
    public int nlenght 
    { 
     get 
     { 
      return _names.Length; 
     } 
    } 
} 

}

+3

你目前正試圖聲明兩個具有相同參數的索引器 - 它不應該編譯。請特別注意你所遇到的錯誤 - 「不顯示」並不夠具體。 (我還強烈建議您閱讀.NET命名約定。) –

回答

1

索引器允許使用就像一個數組類。在課程的內部,您可以以任何想要的方式管理一組值。這些對象可以是一組有限的類成員,另一個數組或一些複雜的數據結構。無論該課程的內部實施如何,其數據都可以通過使用索引器一致地獲得。這是一個例子。

實施例:

using System; 

class IntIndexer 
{ 
private string[] myData; 

public IntIndexer(int size) 
{ 
    myData = new string[size]; 

    for (int i=0; i < size; i++) 
    { 
     myData[i] = "empty"; 
    } 
} 

public string this[int pos] 
{ 
    get 
    { 
     return myData[pos]; 
    } 
    set 
    { 
     myData[pos] = value; 
    } 
} 

static void Main(string[] args) 
{ 
    int size = 10; 

    IntIndexer myInd = new IntIndexer(size); 

    myInd[9] = "Some Value"; 
    myInd[3] = "Another Value"; 
    myInd[5] = "Any Value"; 

    Console.WriteLine("\nIndexer Output\n"); 

    for (int i=0; i < size; i++) 
    { 
     Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]); 
    } 
} 
} 

的IntIndexer類有一個名爲myData的一個字符串數組。這是外部用戶無法看到的私有陣列。該數組在初始化構造函數中,該構造函數接受int大小參數,實例化myData數組,然後使用單詞「empty」填充每個元素。

IntIndexer類有一個名爲myData的字符串數組。這是外部用戶無法看到的私有陣列。該數組在初始化構造函數中,該構造函數接受int大小參數,實例化myData數組,然後使用單詞「empty」填充每個元素。

下一個類成員是索引器,它由此關鍵字和方括號標識爲[int pos]。它接受單個位置參數pos。正如您可能已經猜到的那樣,Indexer的實現與Property相同。它具有與屬性中使用的完全相同的get和setaccessors。該索引器返回一個字符串,如Indexer聲明中的字符串返回值所示。 Main()方法簡單地實例化一個新的IntIndexer對象,添加一些值並打印結果。這裏的輸出:

Indexer Output 

myInd[0]: empty 
myInd[1]: empty 
myInd[2]: empty 
myInd[3]: Another Value 
myInd[4]: empty 
myInd[5]: Any Value 
myInd[6]: empty 
myInd[7]: empty 
myInd[8]: empty 
myInd[9]: Some Value