vb.net函数返回一个运算符

时间:2016-05-13 21:46:58

标签: vb.net

我希望代码返回一个运算符,如(+)或( - ) 然后用它来执行计算。在vb.net中有可能吗?

伪代码

public function rOperator(params) as operator

if (..)
return +

else 
return -
end if

end function 

伪代码

Msgbox(1 rOperator 2)

1 个答案:

答案 0 :(得分:2)

如前所述,这是不可能的。你可以做的是创建一个Func(Of T)的字典,然后通过传入你的运算符来调用它们:

Sub Main
    Dim operations As New Dictionary(Of String, Func(Of Double, Double, Double))()

    'Set up operations for addition, subtractions, multipication, and division
    operations.Add("+", Function(l, r) l + r)
    operations.Add("-", Function(l, r) l - r)
    operations.Add("*", Function(l, r) l * r)
    operations.Add("/", Function(l, r) l / r)

    Dim result As Double = operations("+")(5, 5)
    Dim result2 As Double = operations("*")(5, 5)

    Console.WriteLine(result)
    Console.WriteLine(result2)

End Sub