我正在尝试使用我的控件制作自定义消息框。
public static partial class Msg : Form
{
public static void show(string content, string description)
{
}
}
实际上我需要在这个窗体中放置一些控件(一个 gridview)并且我必须为这个窗口应用我自己的主题,所以我不想使用 MessageBox
。我想从我的其他表单中调用它,比如
Msg.show(parameters);
我不想为此表单创建对象。
我知道我不能从 Form
类继承,因为它不是静态的。但是我想知道 MessageBox
是如何实现的,因为它是静态的。它被称为 MessageBox.show("Some message!");
现在我收到一个错误,因为不允许继承:
Static class 'MyFormName' cannot derive from type 'System.Windows.Forms.Form'. Static classes must derive from object
MessageBox
是如何实现的?
最佳答案
您的表单类不必是 static
.事实上,静态类根本无法继承。
相反,创建一个 internal
派生自 Form
的表单类并提供 public static
显示它的辅助方法。
如果您不希望调用者甚至“知道”底层表单,则此静态方法可以在不同的类中定义。
/// <summary>
/// The form internally used by <see cref="CustomMessageBox"/> class.
/// </summary>
internal partial class CustomMessageForm : Form
{
/// <summary>
/// This constructor is required for designer support.
/// </summary>
public CustomMessageForm ()
{
InitializeComponent();
}
public CustomMessageForm (string title, string description)
{
InitializeComponent();
this.titleLabel.Text = title;
this.descriptionLabel.Text = description;
}
}
/// <summary>
/// Your custom message box helper.
/// </summary>
public static class CustomMessageBox
{
public static void Show (string title, string description)
{
// using construct ensures the resources are freed when form is closed
using (var form = new CustomMessageForm (title, description)) {
form.ShowDialog ();
}
}
}
旁注:如 Jalal points out , 你不必上课 static
为了拥有static
其中的方法。但我仍然会将“帮助程序”类与实际表单分开,这样调用者就无法使用构造函数创建表单(当然,除非它们在同一个程序集中)。
关于c# - 如何创建自定义消息框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6932792/