2017-05-06 72 views
-2

我是一個新手,我試圖在Main中的構造函數中創建Console.Write()數組。我也嘗試將ToString()重寫爲Console.Write()作爲一個字符串數組,但沒有找到一個線索如何做到這一點。使用數組構造函數創建對象

namespace Z1 
{ 
class List 
{ 


    public List(int b) 
    { 
    int[] tabb = new int[b]; 
    Random r1 = new Random(); 
    for(int i=0;i<b;i++) 
    { 
     tabb [i] =r1.Next(0, 100); 
    } 
    } 

    public List() 
    { 
    Random r2 = new Random(); 
    int rInt1=r2.Next(0,10); 
    int[] tabc = new int[rInt1]; 
    Random r3 = new Random(); 
    for(int i=0;i<rInt1;i++){ 
     tabc [i] = r3.Next(0,100); 

    } 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
     List l1 = new List(10); 
     List l2 = new List(); 
     Console.WriteLine(l1.ToString()); 
     Console.WriteLine(l2.ToString()); 

    } 
} 

}

+0

你有沒有嘗試過使用谷歌搜索「如何在C#中覆蓋ToString」? – Abion47

回答

0

你不能只是打印數組,你必須單獨打印每個值。嘗試使用此代替Console.WriteLine();。還請確保您的班級頂部有using LINQ;

l1.ToList().ForEach(Console.WriteLine); 
l2.ToList().ForEach(Console.WriteLine); 
1

第一個要改變的是兩個數組。它們是局部變量,當你從構造函數中退出時,它們被簡單地拋棄,你不能再使用它們。我想你只需要一個可以用你的用戶指定的大小創建的數組,或者用1到10之間的隨機大小創建一個數組。

最後,你可以用通常的方式重載ToString(),並返回Join array

class List 
{ 
    static Random r1 = new Random(); 
    private int[] tabb; 

    public List(int b) 
    { 
     tabb = new int[b]; 
     for (int i = 0; i < b; i++) 
      tabb[i] = r1.Next(0, 100); 
    } 
    // This constructor calls the first one with a random number between 1 and 10 
    public List(): this(r1.Next(1,11)) 
    { } 

    public override string ToString() 
    { 
     return string.Join(",", tabb); 
    } 
} 

現在您的Main方法可以獲得預期的結果。作爲一個便箋,我想這只是一個測試程序,所以沒有太多關注,但是在真實的程序中,我強烈建議您避免創建名稱與框架中定義的類衝突的類。最好避免名稱喜歡列表,任務,隊列等...

相關問題