需要帮助将功能从c#转换为vb.net

时间:2012-10-23 22:36:49

标签: c# vb.net

我需要一些帮助将此代码从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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

您知道Action(Of T1, T2) delegate没有返回值吗?如果它无论如何都是你想要的(虽然我没有看到它的重点,有值类型),你可以使用Sub。

  

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

使用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)
相关问题