I need to create a variable and assign it a message box.
Example:
MessageBox nomatch = MessageBox.Show("No such thing", "Warning");
Is this possible in c# windows forms?
答案 0 :(得分:4)
When i make a search and the input doesn't found a match, this message box appears... And i need to use it for multiple exceptions
MessageBox
doesn't have any public constructor so you can't create it and assign to a variable. But if you want to execute same code in different place, you can declare a Func
delegate like this:
Func<DialogResult> showMsgBox = () => MessageBox.Show("No such thing", "Warning");
And call it wherever you want to show message box:
showMsgBox();
If you don't care about return value you can use Action
instead.
答案 1 :(得分:2)
After reading the comments, I think this is what you may want.
private static void ShowMessageBox(){
MessageBox.Show("No such thing", "Warning");
}
when you need the messagebox, just use
ShowMessageBox()
you can also extend the method to
private static void ShowMessageBox(string msg){
MessageBox.Show(msg, "Warning");
}
show you can input the message you want with ShowMessageBox("Hello World!")
答案 2 :(得分:0)
You cannot create a new instance of the MessageBox class.
Look into the remarks section of below MSDN documentation.
https://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=vs.110).aspx
More over show
returns DialogResult
, which is enum type.