簡體   English   中英

為什么輸出文本框不顯示我的函數給出的返回值?

[英]Why the output textbox doesn't show the return value my function gives?

我打算在文本框中顯示結果。 我的代碼是這樣的:

private void run_Click(object sender, EventArgs e)
{
    GeneticAlgorithm MyGeneticAlgorithm = new GeneticAlgorithm();
    GeneticAlgorithm.GAoutput ShowResult = MyGeneticAlgorithm.GA();

    string output;

    output = ShowResult;

    this.Output.Text = output;
}

class GeneticAlgorithm
{
    public void reset()
    {
        MessageBox.Show("fine");
    }
    public void Initial()
    {
        MessageBox.Show("Good");
    }
    public class GAoutput
    {
        public string Generation;
    }
    public GAoutput GA()
    {
        GAoutput OneGeneration = new GAoutput();
        OneGeneration.Generation = "bad";
        return OneGeneration;
    }
}

運行后,它給我的結果如下:WindowsFormsApplication1.GeneticAlgorithm + GAoutput

有人可以幫幫我嗎? 非常感謝!

您的ShowResult變量不是字符串,因此當您將其分配給一個時,.NET會將其隱式轉換為字符串。 由於沒有ToString()方法,因此它為您提供了泛型類型定義字符串(“WindowsFormsApplication1.GeneticAlgorithm + GAoutput”)。

看起來你想要輸出Generation字段,這一個字符串,所以只需更改:

output = ShowResult;

output = ShowResult.Generation;

它應該開始工作。

此外,如果您不打算為獲得Generation做其他事情,那么您可以真正縮短代碼,一直到:

this.Output.Text = (new GeneticAlgorithm()).GA().Generation;

您可能還想考慮保留GeneticAlgorithm的本地實例,這樣您就不必繼續創建新實例。

您必須確定要為這些類的實例返回的字符串。

然后為每個類重寫ToString()方法以返回相應的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM