下面的代码通过代表元Delegate简化代码的编写,在运行时将调用不同的代表元方法,然后显示相应的运行结果。 在VB.NET中,代表元Delegate有点类似C语言中的指针,也就是说它允许用户传送一个进程的引用,然后调用这些引用的进程。这是一个强有力的编程技术,它将允许用户不再需要If或者是Select语句就可以调用相应的进程,这里的代表元起着桥梁的作用。 新建记事本,下面是代码:
Imports System Imports System.Windows.Forms Public Module mymodule Delegate Sub mydele(ByVal my1 As Int32, ByVal my2 As Int32) Sub main() Dim dele As mydele dele = AddressOf my_add dele.Invoke(10, 20) dele = AddressOf my_sub dele.Invoke(10, 20) dele = AddressOf my_mul dele.Invoke(10, 20) dele = AddressOf my_div dele.Invoke(10, 20) End Sub Public Sub my_add(ByVal num1 As Int32, ByVal num2 As Int32) MessageBox.Show("Add:" & (num1 + num2).ToString, "你好", MessageBoxButtons.OK) End Sub
Public Sub my_sub(ByVal num1 As Int32, ByVal num2 As Int32) MessageBox.Show("Add:" & (num1 - num2).ToString) End Sub
Public Sub my_mul(ByVal num1 As Int32, ByVal num2 As Int32) MessageBox.Show("Add:" & (num1 * num2).ToString) End Sub
Public Sub my_div(ByVal num1 As Int32, ByVal num2 As Int32) MessageBox.Show("Add:" & (num1 / num2).ToString) End Sub
以Delegate.vb保存。 然后编译: vbc /r:System.dll /r:System.Windows.forms.dll Delegate.vb 最后看结果就行了:) |