2011-08-20 29 views
5

我已經搜索過,但我不知道我是否使用正確的措詞進行搜索。我正在用C#爲我的班級編寫一個程序,但我在消息框中遇到了問題。C#消息框,變量用法

我想讓消息框顯示消息並同時讀取一個變量。我在控制檯應用程序中這樣做沒有問題,但是我無法在Windows端找到它。

到目前爲止,我有:

MessageBox.Show("You are right, it only took you {0} guesses!!!", "Results", MessageBoxButtons.OK); 

工作正常。 Howerver我試圖讓{0}成爲變量numGuesses的結果。我確信這很簡單,我只是在書中忽略它,或者我的語法不正確。

+0

'MessageBox.Show(的String.Format( 「你是對的,只用了你{0}猜測!!!」,numGuesses), 「結果」,MessageBoxButtons.OK);' –

回答

1

什麼String.Format()

MessageBox.Show(String.Format("You are right, it only took you {0} guesses!!!", numGuesses), "Results", MessageBoxButtons.OK); 
1

String.Format是你想要什麼:

string message = string.Format("You are right, it only took you {0} guesses!!!",numGuesses) 

MessageBox.Show(message, "Results", MessageBoxButtons.OK); 
1
MessageBox.Show(
        string.Format(
           "You are right, it only took you {0} guesses!!!", 
           Results 
           ), 
        MessageBoxButtons.OK 
       ); 
3

您可以使用String.Format或簡單的字符串連接。

MessageBox.Show(String.Format("You are right, it only took you {0} guesses!!!", myVariable), "Results", MessageBoxButtons.OK); 

http://msdn.microsoft.com/en-us/library/system.string.format(v=VS.100).aspx

級聯:

MessageBox.Show("You are right, it only took you " + myVariable + " guesses!!!", "Results", MessageBoxButtons.OK); 

兩個結果都相當,但您可能更String.Format,如果你有相同的字符串多個變量。

+0

我不會說他們是等效的。格式調用使用stringbuilder而concat創建字符串(可能較慢)。 –

+0

@Anthony Sottile:正確。我應該說,結果是相同的。 –