2015-11-05 23 views
0

我有一個2維數組,我想在方法中返回數組的一行的引用,以便對該行的任何更改都會反映出來在原始數組中。現在我有下面的方法,但是它正在返回值的新實例,因爲傳遞的是雙精度值。如何返回一個雙行的引用[,]

public double[] GetRowReference(int rowNumber) 
{ 
    double[] output = new double[_allPoints.GetLength(1)]; 
    for (int i = 0; i < _allPoints.GetLength(1); i++) 
    { 
     output[i] = _allPoints[rowNumber, i]; 
    } 
    return output; 
} 

如何返回此行作爲參考而不是值?

+0

這是不可能的。 (不幸的是)你最好尋找另一種方式,例如爲什麼不直接使用2d數組? –

+2

另一種方法是使用鋸齒陣列,因此您可以返回內部數組的引用,但您必須更改程序的一部分。 'double [] [] array = new double [2] []; double [] reference = new [] {4d,4,5};數組[1] =參考;參考[1] = 6;' –

+0

@ M.kazemAkhgary我想寫我的API,以便更容易理解行的含義,因此引用整個2d數組中給定行的屬性。我曾考慮過實現鋸齒狀數組,但是我認爲我錯過了2d數組實現。 – PlTaylor

回答

0

您不能返回一個單維數組,其中訪問一個項目訪問另一個二維數組的相應行中的項目。

,你能做的就是創建自己的類型有邏輯,並公開(即通過IList<T>),在其中每個操作映射到一個合適的操作存儲的二維列表上的一維列表的API最好的:

public class ArrayRow<T> : IList<T> 
{ 
    private T[,] array; 
    private int row; 
    public ArrayRow(T[,] array, int row) 
    { 
     this.array = array; 
     this.row = row; 
    } 

    public T this[int index] 
    { 
     get 
     { 
      return array[row, index]; 
     } 
     set 
     { 
      array[row, index] = value; 
     } 
    } 

    public int Count 
    { 
     get { return array.GetLength(1); } 
    } 

    public IEnumerator<T> GetEnumerator() 
    { 
     for (int j = 0; j < array.GetLength(1); j++) 
      yield return array[row, j]; 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 

    //TODO implement remaining IList<T> methods 
}