c# - 如何在函数中使用 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);
}
解决方案
目前还不清楚发生了什么,比如说,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"));
}
推荐阅读
- .net - JSON_QUERY(@data, '$') 仅从 JSON 中获取第一个元素
- visual-studio - 在 Visual Studio 中工作时传递 ./configure 标志
- python - 计算 DataFrame 列中的字数
- android - 如何从geoacast json中获取纬度和经度值
- tableau-api - 带有画面的文档数据库
- performance - URL 是请求大小的一部分吗?
- python - 在保持变量的同时更改 Pandas 中的字符串
- python - 使用 Mac OS 通过 pip install 安装 sklearn 失败
- java - 如何修复日食氧气中缺少的动态网页
- node.js - 如何使用 docker 将应用程序发布到 heroku?