Int*_*ure 10 vb.net function variable-assignment mass-assignment
我知道没有简单的方法来进行多项功能分配VB
,但是我的解决方案是 - 它是好的,你会怎样做得更好?
我需要什么(我将如何在python中做,只是一个例子)
def foo(a) ' function with multiple output
return int(a), int(a)+1
FloorOfA, CeilOfA = foo(a) 'now the assignment of results
Run Code Online (Sandbox Code Playgroud)
我是怎么用VB做的:
Public Function foo(ByVal nA As Integer) As Integer() ' function with multiple output
Return {CInt(nA),CInt(nA)+1}
End Function
Dim Output As Integer() = foo(nA) 'now the assignment of results
Dim FloorOfA As Integer = Output(0)
Dim CeilOfA As Integer = Output(1)
Run Code Online (Sandbox Code Playgroud)
您的解决方案有效,这是一种返回多个结果的优雅方式,但您也可以尝试使用此方法
Public Sub foo2(ByVal nA As Integer, ByRef a1 As Integer, ByRef a2 As Integer)
a1 = Convert.ToInt32(nA)
a2 = Convert.ToInt32(nA) +1
End Sub
Run Code Online (Sandbox Code Playgroud)
并打电话给
foo2(nA, CeilOfA, FloorOfA)
Run Code Online (Sandbox Code Playgroud)
如果要返回很多结果,那么考虑一个可以返回所有需要的值的类是合乎逻辑的(特别是如果这些值具有不同的dataTypes)
Public Class CalcParams
Public p1 As Integer
Public p2 As String
Public p3 As DateTime
Public p4 As List(Of String)
End Class
Public Function foo2(ByVal nA As Integer) As CalcParams
Dim cp = new CalcParams()
cp.p1 = Convert.ToInt32(nA)
.......
Return cp
End Function
Run Code Online (Sandbox Code Playgroud)
对于将来的读者,VB.NET 2017及更高版本现在支持值元组作为语言功能。您可以如下声明函数:
Function ColorToHSV(clr As System.Drawing.Color) As (hue As Double, saturation As Double, value As Double)
Dim max As Integer = Math.Max(clr.R, Math.Max(clr.G, clr.B))
Dim min As Integer = Math.Min(clr.R, Math.Min(clr.G, clr.B))
Dim h = clr.GetHue()
Dim s = If((max = 0), 0, 1.0 - (1.0 * min / max))
Dim v = max / 255.0
Return (h, s, v)
End Function
Run Code Online (Sandbox Code Playgroud)
您这样称呼它:
Dim MyHSVColor = ColorToHSV(clr)
MsgBox(MyHSVColor.hue)
Run Code Online (Sandbox Code Playgroud)
请注意,VB.NET如何创建hue
从调用函数的返回类型推断出的名为public的公共属性。Intellisense也适用于这些成员。
但是请注意,您需要以.NET Framework 4.7为目标。或者,您可以System.ValueTuple
在项目中安装(以NuGet软件包形式提供)以利用此功能。
归档时间: |
|
查看次数: |
48308 次 |
最近记录: |