【问题标题】:C# Message Box, variable usageC# 消息框,变量用法
【发布时间】:2011-08-20 22:16:28
【问题描述】:

我已经搜索过,但我不知道我是否使用了正确的措辞进行搜索。我正在用 C# 为我的班级编写一个程序,但我在使用消息框时遇到了问题。

我试图让消息框显示一条消息并同时读取一个变量。我在控制台应用程序中这样做没有问题,但我无法在 Windows 端解决这个问题。

到目前为止我有:

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

效果很好。但是,我试图让 {0} 成为变量 numGuesses 的结果。我确定这很简单,我只是在书中忽略了它或其他地方,或者我在某个地方的语法不正确。

【问题讨论】:

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

标签: c# variables messagebox


【解决方案1】:

试试

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

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

【讨论】:

    【解决方案2】:

    您可以使用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

    【讨论】:

    • 我不会说它们是等价的。格式调用使用 stringbuilder 而 concat 创建字符串(可能更慢)。
    • @Anthony Sottile:正确。我应该说结果是等价的。
    【解决方案3】:

    String.Format() 呢?

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

    【讨论】:

      【解决方案4】:

      String.Format 是你想要的:

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

      【讨论】:

        【解决方案5】:
        MessageBox.Show(
                          string.Format(
                                         "You are right, it only took you {0} guesses!!!",
                                        Results
                                       ), 
                          MessageBoxButtons.OK
                       );
        

        【讨论】:

          【解决方案6】:

          你的课做得很好,这个帖子很旧。话虽如此,今天你可以这样解决这个问题:

          var firstName = "Sam";
          MessageBox.Show($"My first name is { firstName }.", "First Name", MessageBoxButtons.Ok);
          

          你也可以在 catch 块中使用它:

          ...
          }
          catch (Exception ex)
          {
              MessageBox.Show($"Program encountered an error \n\n{ ex.Message }", "Program Error", MessageBoxButtons.Ok);
          }
          

          基本上任何字符串变量都可以以这种方式使用。不确定返回字符串的函数,但我不明白为什么不。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多