2012-12-27 25 views
3
//program.cs 
foreach (Mutant mutant in mutants) 
{ 
    label12.Text=mutant.displayInfo(); 
} 

//Mutant.cs 
public abstract int dangerQuotient(); 
public String displayInfo() 
{ 
    return(codename + " " + dangerQuotient().ToString()); 
} 

//physicalMutant.cs 
public override int dangerQuotient() 
{ 
    return level * IQ * strength; 
} 

//elementMutant.cs 
public override int dangerQuotient() 
{ 
    return level * region; 

} 

突變體是我的基類,我有兩個派生類physicalMutant和elementMutant。最後,我在label12中獲得elementMutant類的輸出。如何在同一個標​​籤中獲得物理單體的輸出。 通過使用foreach循環內的消息框控件,我可以從兩個派生類中的displayQuotient()獲取值,但通過使用標籤,我只能顯示最後一個迭代值。如何解決此問題?在foreach循環中使用標籤控件在單個標籤中顯示多個值

回答

0

我真的不確定你想要什麼,但如果它是將所有Mutants危險品添加到你的標籤,你將需要改變你的foreach語句到這樣的東西。您目前正在每次迭代foreach循環時更換標籤的內容。

label12.Text = ""; // or just delete the text in the designer 
foreach(Mutant mutant in mutants) 
{ 
    label12.Text += mutant.displayInfo() + "\n"; // This will create a seperate line for each displayInfo 
    // label12.Text += mutant.displayInfo(); //This will add them on the same line 
} 
+0

它的工作,但我得到輸出,隨着label12文本。 –

+0

輸出:label12約翰18艾倫32.從這我需要刪除文本「label12」 –

+0

@RamaPriya你得到什麼輸出?如果它是標籤的起始文本您可以刪除它,請在進入您的foreach循環之前檢查它是否添加「\ n」。第一種方法將完全刪除它,第二種方法將它作爲標題。 –

相關問題