2017-05-06 74 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方法可以获得预期的结果。作为一个便笺,我想这只是一个测试程序,所以没有太多关注,但是在真实的程序中,我强烈建议您避免创建名称与框架中定义的类冲突的类。最好避免名称喜欢列表,任务,队列等...

相关问题