如何重载内置 vb.net 函数
How to overload a built-in vb.net function
我想重载 VB.Net 中的内置 MsgBox()
函数。
我想在每次弹出 MsgBox 时添加一个提示音,但不想创建一个新函数,例如 MsgBoxWithBeep()
,而是在我现有的代码中做一大堆 find/replace .
我可以在一个模块中做到这一点:
Public Sub MsgBox(msg As String)
Beep()
MsgBox(msg)
End Sub
当然,这最终会成为一个无限的递归循环。
我做不到 MyBase.MsgBox()
因为这不是 class。
是否假设 class 所有内置函数都像这样使用,这样我就可以做一些类似 VbNetBaseClass.MsgBox()
的事情或通过其他方式返回到原始函数?
我认为您无法覆盖或重载 MsgBox()
方法,因为它是 static
和标准模块(与 class 相对) as seen here within the source :
[StandardModule]
public sealed class Interaction
{
/* Other methods omitted for brevity */
public static MsgBoxResult MsgBox(object Prompt, MsgBoxStyle Buttons = MsgBoxStyle.ApplicationModal, object Title = null);
}
你最好的选择是编写你自己的方法或包装器来处理用你的可选重载等调用它。
一个简单的解决方案是只使用 MsgBox 调用 MessageBox.Show,如下所示:
Public Sub MsgBox(msg As String)
Beep()
MessageBox.Show(msg, Me.Text, MessageBoxButtons.OK)
End Sub
或者更好的是,使用 exclamation/error 已经发出哔声的图标:
Public Sub MsgBox(msg As String)
MessageBox.Show(msg, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Sub
_
Edit: good point from blackwood...you can make it into a function if you need the result:
Public Function MsgBox(msg As String, _
Optional title As String = "", _
Optional msgButtons As MessageBoxButtons = MessageBoxButtons.OK, _
Optional msgIcon As MessageBoxIcon = MessageBoxIcon.None) _
As System.Windows.Forms.DialogResult
Return MessageBox.Show(msg, title, msgButtons, msgIcon)
End Function
我想重载 VB.Net 中的内置 MsgBox()
函数。
我想在每次弹出 MsgBox 时添加一个提示音,但不想创建一个新函数,例如 MsgBoxWithBeep()
,而是在我现有的代码中做一大堆 find/replace .
我可以在一个模块中做到这一点:
Public Sub MsgBox(msg As String)
Beep()
MsgBox(msg)
End Sub
当然,这最终会成为一个无限的递归循环。
我做不到 MyBase.MsgBox()
因为这不是 class。
是否假设 class 所有内置函数都像这样使用,这样我就可以做一些类似 VbNetBaseClass.MsgBox()
的事情或通过其他方式返回到原始函数?
我认为您无法覆盖或重载 MsgBox()
方法,因为它是 static
和标准模块(与 class 相对) as seen here within the source :
[StandardModule]
public sealed class Interaction
{
/* Other methods omitted for brevity */
public static MsgBoxResult MsgBox(object Prompt, MsgBoxStyle Buttons = MsgBoxStyle.ApplicationModal, object Title = null);
}
你最好的选择是编写你自己的方法或包装器来处理用你的可选重载等调用它。
一个简单的解决方案是只使用 MsgBox 调用 MessageBox.Show,如下所示:
Public Sub MsgBox(msg As String)
Beep()
MessageBox.Show(msg, Me.Text, MessageBoxButtons.OK)
End Sub
或者更好的是,使用 exclamation/error 已经发出哔声的图标:
Public Sub MsgBox(msg As String)
MessageBox.Show(msg, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Sub
_
Edit: good point from blackwood...you can make it into a function if you need the result:
Public Function MsgBox(msg As String, _
Optional title As String = "", _
Optional msgButtons As MessageBoxButtons = MessageBoxButtons.OK, _
Optional msgIcon As MessageBoxIcon = MessageBoxIcon.None) _
As System.Windows.Forms.DialogResult
Return MessageBox.Show(msg, title, msgButtons, msgIcon)
End Function