2016-07-26 55 views
0
class Program 
{ 
    static void Main(string[] args) 
    { 
     IntIndexer myIntIndexer = new IntIndexer(5); 
     for (int i = 0; i < 5; i++) 
     { 
      Console.WriteLine(myIntIndexer[i]); 
     } 
    } 
} 
class IntIndexer 
{ 
    private string[] myData; 

    public IntIndexer(int size) 
    { 
     myData = new string[size]; 
     for (int i = 0; i < size; i++) 
     { 
      Console.WriteLine("Enter an antry"); 
      myData[i] = Console.ReadLine(); 
      Console.WriteLine("---------------------------------"); 
     } 
    } 
} 

初始化當我編譯我得到一個錯誤,不能辦理與[]索引到什麼是錯我的代碼類型IntIndexer的表達?此錯誤來自Console.WriteLine(myIntIndexer[i]);如何打印出從類對象數組,在構造

+0

你的問題是在這裏'Console.WriteLine(myIntIndexer [i])'。你的變量不是容器 –

+0

你的'IntIndexer'類沒有索引器。有關更多信息,請參閱[this](https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx)文章。 –

回答

3

您的類型IntIndexer是一類,但您嘗試通過語句myIntIndexer[i]將其作爲您的類的數組訪問。你不得不暴露在類和訪問字符串代替,因爲它似乎要訪問string作爲字符數組:

public string[] myData; 

Console.WriteLine(myIntIndexer.myData[i]); 
1

的問題是在這裏:

Console.WriteLine(myIntIndexer[i]); 

您試圖在你的IntIndexer彷彿實例是一個數組本身例如使用索引,但類只ç將作爲私有字段添加到數組中。你需要以某種方式暴露這一點,要做到這一點的方法之一是創建具有訪問屬性:

public string[] MyData 
{ 
    get { return myData; } 
} 

然後,你可以這樣調用:

Console.WriteLine(myIntIndexer.MyData[i]); 
1

您正在訪問您的實例就像一個數組,你可以公開像提到的其他答案的陣列或提供索引屬性來訪問數組的內容

public string this[int index] 
{ 
    get 
    { 
      return myData[i]; 
    } 
} 

這會給你的能力來索引到您的實例像你目前正在做的你的回答