【问题标题】:Using a MessageBox in Visual Studio 2010 how can I display a message, a timer int and then another message?在 Visual Studio 2010 中使用 MessageBox 如何显示一条消息、一个计时器 int 和另一条消息?
【发布时间】:2012-12-18 04:12:33
【问题描述】:

我正在制作一个小型迷宫游戏,但遇到了一个小问题他们玩游戏需要多长时间。我的消息框代码是:

MessageBox.Show("Congratulations! You've beaten the maze! It took you: "+gameElapsed); 

gameElapsed 是我的计时器的整数。它在文本没问题后显示秒数,之后只是收到文本说“秒”是我遇到的问题。

所以我希望 MessageBox 说“恭喜!你已经通过了迷宫!你花了:X 秒”

X 是 gameElapsed,计时器 int。

我希望我已经足够清楚地解释了我的问题,提前感谢您的帮助。

【问题讨论】:

  • 对不起,请您说明一下您到底想做什么? :)
  • 所以 gameElapsed 是一个 int 包含他们花费的秒数?

标签: c# visual-studio-2010


【解决方案1】:

我认为string.Format 更好:

MessageBox.Show(string.Format("Congratulations! You've beaten the maze! It took you: {0} seconds", gameElapsed));

使用 非文字字符串上的 + 运算符会导致在运行时执行连接。
连接 在运行时将多个字符串放在一起,避免使用 + 运算符,因为它会创建多个 垃圾收集堆上的字符串对象。
相反,使用System.Text.StringBuilder 类型或使用string.Format 方法。 (string.Format 内部使用System.Text.StringBuilder。)

因此我建议:

  • 对少量字符串使用string.Format,或者我们需要高水平的可读性。
  • 对大量字符串使用System.Text.StringBuilder
  • + 用于文字字符串,C# 编译器在编译时将它们连接起来,最后只放置一个字符串。

【讨论】:

  • @regulatethis 我已经更新了我的答案。希望它对你有意义。
【解决方案2】:

你试过了吗:

MessageBox.Show("Congratulations! You've beaten the maze! It took you: "+ gameElapsed + " Seconds");

【讨论】:

    【解决方案3】:
    MessageBox.Show("Congratulations! You've beaten the maze! It took you: "+gameElapsed.ToString() + " seconds"); 
    

    将打印出来:

    恭喜!你打败了迷宫!你花了:4 秒

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      相关资源
      最近更新 更多