将引用传递给数组的一部分 [英] Passing reference to part of an array
问题描述
大家好
我正在尝试为自定义数学计算编写一个共享方法.它引用一个数组作为计算的输入.但是,我只需要能够对数组的一部分执行计算,因此我需要能够以某种方式将该信息传递给方法.我已经做了一个简短的示例来解释我的意思,并且您会看到函数调用试图在0列中指示该函数使用数组dataArray的第2行到第3行.
Hello all
I am trying to write a shared method for custom math calculations. It takes reference to an array as input for the calculations. However, I need to be able to perform the calculations on only part of my array, and so I need to be able to pass that information to the method somehow. I have made a short example to explain what I mean, and you''ll see the function call trying to indicate for the function to use the array dataArray''s rows 2 through 3, in column 0.
Module Module1
Sub Main()
Dim dataArray(5,1) As Double
''Create dummy data
For i = 0 To 5
dataArray(i,0) = i ^ 1.3
Next
''Perform calculation
Dim b As Double = mySum(dataArray(2..3, 0))
End Sub
End Module
Module myMath
Function mySum(ByRef scalar() As Double) As Double
Dim _sum As Double
For i = 0 To scalar.Length - 1
_sum = _sum + scalar(i)
Next i
Return _sum
End Function
End Module
另外,函数是否有简单的方法将数组直接返回到现有数组中?伪代码:
Also, is there a simple way for a function to return an array directly into an existing array? Pseudo code:
dataArray(2..3,1) = mySum(dataArray(2..3,0))
其中
where
Function mySum(ByRef scalar() as double) as double()
由于这种类型的计算将运行数小时,因此出于性能原因,我试图避免创建和传递新数组.
希望您对解决此问题有任何建议.
干杯
As this type of calculations will be running for hours, I''m trying to avoid creating and passing new arrays for performance reasons.
Hope you have any tips on how to solve this.
Cheers
推荐答案
为什么不传递您感兴趣的数组子集的边界.
另外,您正在通过ref传递数组,所以我不确定在传递数组副本方面您担心的问题是什么.
Why not pass the boundaries of the subset of the array that you are interested in.
Also, you are passing the array by ref, so I''m not sure what the issue is that you are worried about in terms of passing copies of the array.
Module Module1
Sub Main()
Dim dataArray(5) As Double
'Create dummy data
For i = 0 To 5
dataArray(i) = i ^ 1.3
Next
'Perform calculation
Dim first As Integer = 2
Dim last As Integer = 3
Dim b As Double = mySum(dataArray, first, last)
End Sub
Function mySum(ByRef scalar() As Double, ByVal first As Integer, ByVal last As Integer) As Double
Dim _sum As Double
For i = first To last
_sum = _sum + scalar(i)
Next i
Return _sum
End Function
End Module
希望有帮助.
-Rd
Hope that helps.
-Rd
谢谢你,理查德.
我看到这也是Microsoft在其数组类中实现方法的方式,将边界作为方法中的参数传递.
另外,我对ArraySegment进行了快速浏览,这给了我希望的功能类型以希望,但是它的实现有些欠缺.
再次感谢
-Fossie
Thank you, Richard.
I see this is the way Microsoft implemented methods in their array class too, passing the boundaries as arguments in the method.
Also, I had a quick peek on ArraySegment which gave me a passing hope for the type of functionality I wanted, but it''s implementation was somewhat lacking.
Thanks again
-Fossie
这篇关于将引用传递给数组的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!