簡體   English   中英

創建並傳遞自定義函數作為委托(VB.NET 2005)

[英]Create and pass custom function as a delegate (VB.NET 2005)

我有一個函數Process(data, f) ,其中data是常規參數, f是處理數據所需的函數(作為對Process的委托傳遞)

f的簽名是int f(a,b,c) ,Process在調用委托時提供abc

直到這里,都是標准的委托用法。

現在,我有一個特殊但很常見的情況,我想用常量f函數調用Process。 因此,我想編寫SimpleProcess(data, k)以便在這種情況下調用方無需創建委托,只需傳遞常數k(唯一需要的信息)即可。

因此,我需要動態創建一個常量函數g(a,b,c) ,該函數需要3個參數(將被忽略)並始終返回k 這必須在SimpleProcess函數中完成,這樣我就可以從該函數中簡單地調用Process(data, g) ,而無需為此特殊情況重寫整個Process函數。

這有可能嗎,我如何實現呢?

謝謝。

編輯:好的,我沒有在標題中發現“ 2005”位。 我最初的答案是稍后(在線下)-這是VB.NET 2005的完整答案。

您可以創建一個保存常量值的類(或結構,我想),然后使用AddressOf將該類型的函數轉換為委托。 您可以通過創建Shared函數將這兩個步驟放在一起來簡化此過程。

這是一個簡短但完整的程序來演示這一點:

Public Delegate Function Function3 (ByVal x As Integer, _
    ByVal y As Integer, ByVal z As Integer) As Integer

Public Class Constant

    Private value As Integer

    Public Sub New (ByVal value As Integer)
      Me.value = value    
    End Sub

    Public Function ReturnValue(ByVal x As Integer, _
        ByVal y As Integer, ByVal z As Integer) _
        As Integer
      Return value
    End Function

    Public Shared Function CreateFunction _
        (ByVal x As Integer) As Function3    
      Dim c As Constant = New Constant(x)
      return AddressOf c.ReturnValue
    End Function

End Class

Public Module Test
    Public Sub Main
      Dim func As Function3 = Constant.CreateFunction(3)
      Console.WriteLine(func(8, 9, 10))
    End Sub
End Module

在您的情況下,您可以將其用於:

Process(data, Constant.CreateFunction(g))

原始答案

您可以使用lambda表達式,盡管它具有三個參數,但並不是很好:

Process(data, Function(x as Integer, y as Integer, z as Integer) g)

另一種選擇是編寫返回函數的函數,該函數返回常量:

Public Function Constant(value as Integer) As MyDelegateType
    Return Function(x as Integer, y as Integer, z as Integer) value
End Function

然后調用:

Process(data, Constant(g))

抱歉,如果某些語法稍有偏離-我不是VB人士。

您是否考慮過將功能分為兩個具有不同簽名的功能。 我假設您的委托函數將返回常量提供的值。

因此,您的方法的委托版本將僅執行計算“恆定”值所需的處理。

    Function Process(ByVal data As Object, ByVal f As MyDelegate) As Object
    Dim k As Integer
    ' Calculate k

    Return Process(data, k)
End Function

Function Process(ByVal data As Object, ByVal k As Integer) As Object
    Dim stuff As Object

    ' do stuff with k
    Return stuff
End Function

Delegate Function MyDelegate(ByVal a As Object, ByVal b As Object, ByVal c As Object) As Integer

鑒於較新的語言支持lambda表達式,一種似乎過時的方法是創建一些委托工廠的通用類。 對於三個可變參數的函數,我還沒有做過,但是這種方法很容易適應這種情況。 這種方法有點像@Jon Skeet:的上述答案,但是要使用我的通用工廠之一(如果我將其擴展為三個變量加一個固定參數),您將要做的就是定義一個帶有四個參數的函數並簡單地返回最后一個,然后使用以下命令創建所需的委托(例如,值為19)

Process(data, FunctionOf(of Integer, Integer, Integer, Integer).NewInv(of Integer)(AddressOf FunctionToReturnLastValue, 19))

請注意,與Lambda表達式不同,可以在不使編輯並繼續無效的情況下添加,更改或刪除上述代碼(請注意,可以推斷出(整數)的最后一個)。 也與lambda不同,固定參數值是在創建委托時評估的,而不是在調用它們時評估的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM