【发布时间】:2026-01-06 07:35:01
【问题描述】:
我正在制作我自己的消息框类(称为 MessageBoxC,等等),并且像 System.Windows.Forms.MessageBox 一样,我想让我的类没有构造函数并且不可能声明它的新实例。
例如:
Public Class MessageBoxC
Public Overloads Sub Show(ByVal message As String)
Me.Message = message
ProcessData() '(*)
Me.ShowDialog()
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
System.Windows.Forms.MessageBox.Show("Hello World!") 'works fine
MessageBoxC.Show("Hello World!") 'works fine
Dim msgBox As New System.Windows.Forms.MessageBox 'and you'll get an error message here (**)
Dim msgBoxC As New MessageBoxC 'no error message
End Sub
End Class
(*) 不重要。它只是根据需要计算文本大小(以像素为单位的宽度和高度)以纠正表单大小,并且相应的标签获取 Me.Message 属性的值。
(**) 这就是我的意思。您不能创建 MessageBox 类的新实例,您将收到以下错误消息:“Type System.Windows.Forms.MessageBox 没有构造函数。” 好吧,我的类也没有构造函数,但可以声明它的一个实例。这里有什么诀窍?
非常感谢!
解决了。感谢 OneFineDay。
Public Class MessageBoxC
Private Sub New()
'Empty
End Sub
Public Overloads Shared Function Show(ByVal message As String) As System.Windows.Forms.DialogResult
Return Show(message, Constants.MyAppName, Constants.messageTitle, MessageBoxCButtons.OK, MessageBoxCIcon.Undefined)
End Function
Public Overloads Shared Function Show(ByVal message As String, _
ByVal caption As String, _
ByVal title As String, _
ByVal buttons As Library.MessageBoxCButtons, _
ByVal icon As Library.MessageBoxCIcon) As System.Windows.Forms.DialogResult
Dim msgBoxC As New CBox(message, caption, title, buttons, icon)
msgBoxC.ShowDialog()
Return msgBoxC.DialogResult
End Function
Private Class CBox
Inherits System.Windows.Forms.Form
Sub New(ByVal message As String, _
ByVal caption As String, _
ByVal title As String, _
ByVal buttons As Library.MessageBoxCButtons, _
ByVal icon As Library.MessageBoxCIcon)
MyBase.New()
InitializeComponent()
Me.Message = message
Me.Text = caption
Me.Title = title
Me.Buttons = buttons
Me.Icon64 = icon
Me.OptimizeMe()
End Sub
End Class
End Class
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim dialogResult As New DialogResult
dialogResult = MessageBoxC.Show("This is a simple message.")
MessageBox.Show(dialogResult.ToString)
End Sub
End Class
【问题讨论】:
-
P.S.我的 MessageBoxC 类继承 System.Windows.Forms.Form。我知道基类已经有一个构造函数,但是除了“绘制”一个新类之外,如何避免它。
-
Messagebox.Show(包含在框架中)是一种共享(静态)方法,其代码类似于Dim msgbox As New MessageBox : msgbox.Label.Text = "Hello" : msgbox.ShowDialog() : msgbox.Dispose。所以它当然会创建一个新的表单实例——它只是在一个公共的、静态的接口中这样做,所以作为程序员你不需要关心它。
标签: vb.net class constructor instance declare