2012-06-08 35 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

相關問題