2014-11-03 31 views
0

對不起,如果標題和問題不清楚;我沒有一個好的方式來描述它。但這裏是:混淆ParamArray行爲 - 重複數組以某種方式鏈接?

所以發生的事情是「testMat」以某種方式連接在一起,即使我沒有重新定義它們,它也會使值發生變化。例如,如果你在下面運行這個代碼,你會發現在testResult的matSum函數中,out1和out2的值正在改變(在循環中),我不知道爲什麼!它們的值在testResult1中不會改變。這種行爲從何而來?

Sub Main() 

    Dim testMat As Double(,) = {{1, 2}, {3, 4}} 

    Dim testResult As Double(,) = matSum(testMat, testMat, testMat) 
    Dim testResult1 As Double(,) = matSum({{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}) 

End Sub 


Function matSum(ByVal ParamArray args As Double()(,)) As Double(,) 
    'This function sums matrices. It assumes you know how to sum matrices. 

    Dim m, n As Integer 
    Dim out, out1, out2 As Double(,) 
    Dim numArgs As Integer = args.Length 

    out = args(0) 
    out1 = args(1) 
    out2 = args(2) 
    m = out.GetUpperBound(0) 
    n = out.GetUpperBound(1) 

    For v As Integer = 1 To numArgs - 1 
     For i As Integer = 0 To m 
      For j As Integer = 0 To n 
       out(i, j) = out(i, j) + args(v)(i, j) 
      Next 
     Next 
    Next 

    Return out 

End Function 
+1

數組是一個引用類型,這就是它發生的原因。它與'ParamArray'無關。 – MarcinJuraszek 2014-11-03 03:20:22

+0

對不起,你能詳細說一下嗎?我以爲我讀到ParamArray只是ByVal? (或者這不是你指的?) – Esteban 2014-11-03 03:25:13

+0

'ByVal',你不能改變'args'的身份(例如,你不能讓'args'指向一個新的或不同的數組),但是你可以改變它的內容 - 即數組元素。 – 2014-11-03 03:33:16

回答

1

好吧,讓它多一點上下文。

數組是參考類型,所以當它通過時ByVal正在傳遞的值是參考。該數組未被複制或克隆。參考是。但它仍然指向內存中的同一個數組。

現在,當你在這裏調用你的方法。

Dim testResult As Double(,) = matSum(testMat, testMat, testMat) 

outout1out2具有相同的值 - 參照testMat。使用這些變量中的任何一個修改該數組中的值將修改相同的數組,並且您還會從其他參考中看到它。

+1

謝謝,我想我明白了。當Matlab是您的主要「語言」時,這些就是您遇到的問題。 – Esteban 2014-11-03 04:28:25