2012-03-02 88 views
0

我有一个“总是”按顺序运行步骤A,C,D的算法。VB.NET - 钩子机制,或者如何执行一系列方法?

我想允许一种方式来运行A,B,C,D,其中B可以是多种方法。 C,D“应该”不受影响,但我不能并行化。它只是写入一个文件。

任何方式,我知道一些关于代表,并已使用AddressOf挂钩事件处理程序。

所以我想创建一个数组或收集什么不是“地址”或委托。

这甚至可能吗?

这是'最好的'方法吗?我知道如何强制对象的行为,但我希望重用已经内置到VB,.NET的任何机制。

戴恩

回答

1

您可以简单地使用一个事件来存储和调用多个方法。事件基本上是流线型多播委托,所以你不必使用Delegate.Combine。缺点是你的方法不能有返回类型。

以下是另一种使用多播委托的方法。这个例子假定你想从方法中返回一个值。如果你不需要这个,你将不必循环遍历这些方法;你可以使用myMethods.Invoke

'the methods will be stored here 
Private _MyMethods As [Delegate] 

'this is here to show the signature of the methods 
Public Delegate Function MyMethod(ByVal input As String) As String 

Public Sub AddMethod(ByVal method As MyMethod) 
    _MyMethods = [Delegate].Combine(_MyMethods, method) 
End Sub 

Public Sub RemoveMethod(ByVal method As MyMethod) 
    _MyMethods = [Delegate].Remove(_MyMethods, method) 
End Sub 

Public Sub InvokeMethods(ByVal input As String) 
    If _MyMethods Is Nothing Then Return 

    Dim myMethods As MyMethod = DirectCast(_MyMethods, MyMethod) 

    'since you'll want the return value of each methods, loop through the methods 
    For Each method As MyMethod In myMethods.GetInvocationList() 
     Dim value As String = method.Invoke(input) 

     'TODO: something with the value 
    Next 
End Sub 

的另一个替代上面调用代码,你可以使用Delegate.DynamicInvoke方法没有投委托。然而,这将使用后期绑定,并且在一个函数的情况下,无论如何都需要返回值。

+0

从Gideon Engelberth和Timiz0r学习,但不得不选择一个。谢谢先生们。 – Danedo 2012-03-03 14:54:19

1

这不是你经常看到的东西,但让调用当单个委托变量调用多个功能,你可以结合的代表。

Dim midAction As Action(Of String) = AddressOf Console.WriteLine 
Dim m1 As New IO.StreamWriter(New IO.MemoryStream()) 
m1.AutoFlush = True 
Dim m2 As New IO.StreamWriter(New IO.MemoryStream()) 
midAction = CType([Delegate].Combine(New Action(Of String)(AddressOf Console.WriteLine), 
            New Action(Of String)(AddressOf m1.WriteLine), 
            New Action(Of String)(Sub(s) 
                  m2.WriteLine(s) 
                  m2.Flush() 
                  End Sub)), 
        Action(Of String)) 
midAction("test") 

这里最大的缺点是Delegate.Combine的无类型使得所有铸件都是必需的。

代表们的IEnumerable也会工作,更强烈地表示您要调用多个函数。

从你的描述中,我想我会坚持一个委托参数,因为它似乎是更好的匹配参数的语义。调用者可以在具有需要在中间调用的多个函数时进行组合。