首页 > 解决方案 > 如何在函数中使用 MessageBox

问题描述

我试图让函数接收两个字符串并显示消息框:

public void Myfunction (string str1, string str2)
     {
         MessageBox.Show("your message was " + str1 + Environment.NewLine + str2);
     }

private void Btn_Display_Click(object sender, RoutedEventArgs e)
    {
        string today;
        today = DateTime.Now.ToString("dd/MM/yyyy");
        myfunction(TextBox_Msg.Text, today);
    }

标签: c#

解决方案


目前还不清楚发生了什么,比如说,myfunction应该做什么?函数计算值。我建议一次性显示消息:

    private void Btn_Display_Click(object sender, RoutedEventArgs e) {
      // Show message - MessageBox.Show 
      // of several lines - string.Join(Environment.NewLine
      //   1st line "your message was" + TextBox_Msg.Text
      //   2nd line DateTime.Now in "dd/MM/yyyy" format
      MessageBox.Show(string.Join(Environment.NewLine, 
        $"your message was {TextBox_Msg.Text}", 
          DateTime.Now.ToString("dd/MM/yyyy")));
    }

如果您坚持提取方法,那么我们先将其重命名为 - ShowMessageLines

// Let's show arbitrary many lines (whe only 2?)
// Let's accept all types (not necessary strings)
public static void ShowMessageLines(params object[] lines) {
  // public method - input arguments validation
  if (null == lines)
    throw new ArgumentNullException(nameof(lines));

  // Combine all lines into textToShow
  // First line must have a prefix - "your message was " 
  string textToShow = string.Join(Environment.NewLine, lines
    .Select((text, index) => index == 0 
       ? $"your message was {text}"
       :   text?.ToString()));

  MessageBox.Show(textToShow);
}

...

private void Btn_Display_Click(object sender, RoutedEventArgs e) {
  ShowMessageLines(
    TextBox_Msg.Text, 
    DateTime.Now.ToString("dd/MM/yyyy"));
}

推荐阅读