Delegate类
表示委托,委托是一种数据结构,它引用静态方法或引用类实例及该类的实例方法。
System.Object
System.Delegate
System.MulticastDelegate
<Serializable>
<ClassInterface(ClassInterfaceType.AutoDual)>
MustInherit Public Class Delegate
Implements ICloneable, ISerializable
Delegate 类是委托类型的基类。
然而,只有系统和编译器可以显式地从 Delegate 类或 MulticastDelegate 类派生。
此外,还不允许从委托类型派生新类型。
Delegate 类不是委托类型,该类用于派生委托类型。
大多数语言实现 delegate 关键字,
这些语言的编译器能够从 MulticastDelegate 类进行派生。
所以,用户应当使用语言所提供的delegate 关键字。
委托类型的声明建立了一个协定,
该协定指定一个或多个方法的签名。
委托是委托类型的实例,它引用下面的一项或多项:
不为空引用(Visual Basic 中为 Nothing)的目标对象和该目标对象的实例方法。
静态方法
仅当方法的签名与委托类型所指定的签名完全匹配时,委托才能引用方法。
当委托引用实例方法时,委托存储对该方法入口点的引用及对称为目标的对象的引用,
该对象是对其调用该方法的类实例。
实例方法的目标不能为空引用 (Nothing)。
当委托引用静态方法时,委托存储对该方法入口点的引用。静态方法的目标为空引用 (Nothing)。
委托的调用列表就是已排序的委托集,
其中列表的每个元素恰好调用该委托调用的一个方法。
调用列表可以包含重复的方法。
在调用期间,委托按方法出现在调用列表中的顺序来调用方法。
委托试图调用其调用列表中的每个方法,而重复方法在调用列表中出现一次就调用一次。
委托是不可变的;一旦创建,委托的调用列表便无法更改。
委托可以是多路广播(可组合)或单路广播(不可组合)。
多路广播(可组合)委托调用一个或多个方法,且可以用于合并操作。
单路广播(不可组合)委托只能调用一个方法,且不可用于合并操作。
单路广播委托 A 的调用列表只包含一个元素,即对 A 的引用。
合并操作(如 Combine 和 Remove)并不改变现有委托。
相反,这样的操作返回一个新委托,其中包含操作结果、未更改的委托或空引用 (Nothing)。
当合并操作的结果是没有引用任何方法的委托时,该操作返回空引用 (Nothing)。
当所请求的操作无效时,合并操作返回未更改的委托。
如果所调用的方法引发异常,则方法停止执行,
并将异常向回传递给委托的调用方,且不再调用调用列表中其余的方法。
捕捉调用方的异常并不改变此行为。
当委托所调用的方法的签名包含返回值时,委托返回调用列表中最后一个元素的返回值。
当签名包含由引用传递的参数时,该参数的最终值就是调用列表中每个方法的结果,这些方法依序执行并更新参数的值。
编译器为委托提供两种其他方法:
在 C 或 C++ 中与委托最为相似的是函数指针。
然而,函数指针只能引用静态函数,而委托可以引用静态方法和实例方法。
当委托引用实例方法时,委托不仅存储对方法入口点的引用,还存储对为其调用该方法的类实例的引用。
与函数指针不同,委托是面向对象、
[Visual Basic]
Imports System
Public Class SamplesDelegate
' Declares a delegate for a method that takes in an int and returns a String.
Delegate Function myMethodDelegate(myInt As Integer) As [String]
' Defines some methods to which the delegate can point.
Public Class mySampleClass
' Defines an instance method.
Public Function myStringMethod(myInt As Integer) As [String]
If myInt > 0 Then
Return "positive"
End If
If myInt < 0 Then
Return "negative"
End If
Return "zero"
End Function 'myStringMethod
' Defines a static method.
Public Shared Function mySignMethod(myInt As Integer) As [String]
If myInt > 0 Then
Return "+"
End If
If myInt < 0 Then
Return "-"
End If
Return ""
End Function 'mySignMethod
End Class 'mySampleClass
Public Shared Sub Main()
' Creates one delegate for each method.
Dim mySC As New mySampleClass()
Dim myD1 As New myMethodDelegate(AddressOf mySC.myStringMethod)
Dim myD2 As New myMethodDelegate(AddressOf mySampleClass.mySignMethod)
' Invokes the delegates.
Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 5, myD1(5), myD2(5))
Console.WriteLine("{0} is {1}; use the sign ""{2}"".", - 3, myD1(- 3), myD2(- 3))
Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 0, myD1(0), myD2(0))
End Sub 'Main
End Class 'SamplesDelegate
'This code produces the following output:
'
'5 is positive; use the sign "+".
'-3 is negative; use the sign "-".
'0 is zero; use the sign "".