2011-05-24 85 views
3

是否可以爲返回數組的特定元素的2D數組編寫屬性?我很確定我不在尋找索引器,因爲它們的數組屬於靜態類。2D數組屬性

+2

無法獲取您的問題,請精心製作 – 2011-05-24 13:20:40

回答

6

這聽起來像你想要一個帶參數的屬性 - 這基本上是一個索引器。但是,您不能在C#中編寫靜態索引器。

當然你可能只是寫一個屬性返回數組 - 但我假設你不想這樣做的原因封裝。

另一種方法是編寫GetFoo(int x, int y)SetFoo(int x, int y, int value)方法。

還有一種替代方案是在陣列周圍編寫一個包裝類型,並返回作爲屬性。該包裝類型可以有一個索引 - 也許只是一個只讀之一,例如:

public class Wrapper<T> 
{ 
    private readonly T[,] array; 

    public Wrapper(T[,] array) 
    { 
     this.array = array; 
    } 

    public T this[int x, int y] 
    { 
     return array[x, y]; 
    } 

    public int Rows { get { return array.GetUpperBound(0); } } 
    public int Columns { get { return array.GetUpperBound(1); } } 
} 

然後:

public static class Foo 
{ 
    private static readonly int[,] data = ...; 

    // Could also cache the Wrapper and return the same one each time. 
    public static Wrapper<int> Data 
    { 
     get { return new Wrapper<int>(data); } 
    } 
} 
+0

我以爲我們不能通過屬性返回數組? http://msdn.microsoft.com/en-us/library/0fss9skc%28v=VS.100%29.aspx忽略這一點,你回答了我的問題。 – Andrew 2011-05-24 13:25:55

+0

@Andrew:*不能*和*不應該*不是一回事。你*可以*返回一個數組的引用 - 但是你無法控制數組的使用方式。 – 2011-05-24 13:27:24

+0

我假設屬性實現應該讀取'return array [x,y];',而不是'return this [x,y];'(這會給出無限遞歸)。 – Douglas 2013-06-23 16:21:50

1

你的意思是這樣嗎?

array[x][y] 

其中x是行而y是列。

0

也許這樣的事情?:

public string this[int x, int y] 
{ 
    get { return TextArray[x, y]; } 
    set { TextArray[x, y] = value; } 
} 
+0

問題在於它處於靜態類中,因此必須是靜態成員。您不能在C#中創建靜態索引器。 – 2011-05-24 13:27:53