2012-06-08 65 views
-6
public partial class Form1 : Form 
{ 
    Course[] csharp = new Course[5];  

    public Form1() 
    { 
     InitializeComponent(); 
    }   

    private void Form1_Load(object sender, EventArgs e) 
    { 
     Test c1 = new Test("Quiz", 
      new DateTime(2012, 6, 6), 86); 
     Test c2 = new Test("Mid-Term", 
      new DateTime(2012, 5, 6), 90); 
     Test c3 = new Test("Final", 
      new DateTime(2012, 4, 6), 87); 
     Test c4 = new Test("Quiz", 
      new DateTime(2012, 3, 6), 100); 
     Test c5 = new Test("Quiz", 
      new DateTime(2012, 2, 6), 66); 
    } 
} 

如何将我的测试c5添加到我的对象数组csharp?我想为三个对象添加五个测试类型。请帮助我在初学者水平。持有值的对象。我需要添加五个测试到我的对象

+3

这是功课吗? –

+1

您不能将“Test”类型的对象添加到“Course”类型的数组中。 – Nailuj

+0

我需要用五个测试来填充课程对象,同时使用具有三个字段的测试课程。 –

回答

3

您可以声明数组,并使用一个值分配给它的array initializer syntax如下:

Test[] tests = { 
    new Test("Quiz", new DateTime(2012, 6, 6), 86), 
    new Test("Mid-Term", new DateTime(2012, 5, 6), 90), 
    new Test("Final", new DateTime(2012, 4, 6), 87), 
    new Test("Quiz", new DateTime(2012, 3, 6), 100), 
    new Test("Quiz", new DateTime(2012, 2, 6), 66) 
}; 
1

我明白我是一个初学者,有问题就这样!您无法将测试对象添加到课程对象,它们是两个不同的东西!

你需要像

Test[] courseTests = new Test[5]; 

并通过这样

courseTests[1] = new Test("Quiz", new DateTime(2012, 6, 6), 86); 

添加或者你可以使用一个列表List<Test> courseTests = new List<Test>();和使用courseTests.Add


编辑:

我明白你的意思,你需要的东西是这样的:

public Class course 
{ 
    public List<Test> tests = new List<Test>(); 
    //Place other course code here 
} 
public Class Test 
{ 
    public string Name; 
    public Datetime Time; 
    public int Number; 
    Test(string name, Datetime time, int number) 
    { 
Name = name; 
Time = time; 
Number = number; 
    } 
} 

,然后在Main方法也好,做Course.tests.Add(new Test(Blah blah blah));

+0

我想添加五个测试,我有另一类的类型,日期和等级,并将这五个添加到课程对象 –

+2

有没有T [] .Add(T)方法。我想你的意思是在这里使用'List ',或者直接对数组进行索引访问,即T [_index_] = value; – payo

+0

是的,那就是我的意思,我编辑它 – Cyral

0

创建测试[]在您的课程班设置为你想要的尺寸。然后创建一个像这样的无效方法。在下面的代码中,myTests是您的测试数组。希望这可以帮助!

public void addTest(Test a) 
    { 
     for (int i = 0; i < myTests.Length; i++) 
     { 
      if (myTests[i] == null) 
      { 
       //Adds test and leaves loop. 
       myTests[i] = a; 
       break; 
      } 
      //Handler for if all tests are already populated. 
      if (i == myTests.Length) 
      { 
       MessageBox.Show("All tests full."); 
      } 
     } 
    } 

此外,如果要使测试数组的大小动态化,可以使用ArrayList。希望这可以帮助!

+0

您可以从课程实例调用此方法。 – user1442873

相关问题