3

我需要一些帮助将此代码从 c# 转换为 vb.net:

    private static Action<int, int> TranslateOrigin(Action<int, int> f, int x, int y)
    {
        return (a, b) => f(a + x, b + y);
    }

我在互联网上找到的自动翻译器把它弄得一团糟,产生:

Private Shared Function TranslateOrigin(f As Action(Of Integer, Integer), x As Integer, y As Integer) As Action(Of Integer, Integer)
    Return Function(a, b) f(a + x, b + y)
End Function

哪个不会编译,抱怨“表达式不产生值”。我一直在戳它一段时间,但没有任何运气翻译它,任何帮助将不胜感激。

4

3 回答 3

4

我认为这更接近一点,因为它不返回一个值,而是一个动作。使用单行。

Public Shared Function TranslateOrigin(f As Action(Of Integer, Integer), x As Integer, y As Integer) As Action(Of Integer, Integer)
    Return Sub(a, b) f(a + x, b + y)
End Function
于 2012-10-23T22:56:21.917 回答
1

这应该这样做:

Private Shared Function TranslateOrigin(ByVal f As Action(Of Integer, Integer), ByVal x As Integer, ByVal y As Integer) As Action(Of Integer, Integer)
     Return Function (ByVal a As Integer, ByVal b As Integer) 
               f.Invoke((a + x), (b + y))
            End Function
End Function
于 2012-10-23T22:51:34.323 回答
0

您知道Action(Of T1, T2)委托不返回值吗?如果它无论如何都是你想要的(虽然我没有看到太多的意义,有值类型),你可以使用 Sub.

封装具有两个参数且不返回值的方法。

有了一个子,这将给出以下代码:

Private Shared Function TranslateOrigin(f As Action(Of Integer, Integer), x As Integer, y As Integer) As Action(Of Integer, Integer)
    Return Sub(a, b) f(a + x, b + y)
End Function

您可能想要返回一个值,因此您需要一个Func(Of T1, T2, TResult)delegate。在您的情况下,这将使:

Private Shared Function TranslateOrigin(f As Func(Of Integer, Integer, Integer), x As Integer, y As Integer) As Func(Of Integer, Integer, Integer)
    Return Function(a, b) f(a + x, b + y)
End Function

如下调用它,将返回值6(正如我所料):

TranslateOrigin(Function(x, y) x + y, 1, 2)(1, 2)
于 2012-10-23T22:59:53.100 回答