我正在尝试用我的控件制作一个自定义消息框。
public static partial class Msg : Form
{
public static void show(string content, string description)
{
}
}
实际上我需要在此表单中放置一些控件(网格视图),并且我必须为此窗口应用我自己的主题,所以我不想使用MessageBox
。我想从我的其他形式中调用它,例如
Msg.show(parameters);
我不想为此表单创建对象。
我知道我不能继承Form
类,因为它不是静态的。但我想知道如何MessageBox
已实现,因为它是静态的。它被称为像MessageBox.show("Some message!");
现在我收到错误,因为不允许继承:
静态类“MyFormName”无法从类型“System.Windows.Forms.Form”派生。静态类必须从对象派生
How 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 ();
}
}
}
旁注:如贾拉尔指出,你不必上课static
为了有static
里面的方法。但我仍然会将“helper”类与实际表单分开,以便调用者无法使用构造函数创建表单(当然,除非它们位于同一个程序集中)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)