是否可以爲返回數組的特定元素的2D數組編寫屬性?我很確定我不在尋找索引器,因爲它們的數組屬於靜態類。2D數組屬性
2D數組屬性
回答
這聽起來像你想要一個帶參數的屬性 - 這基本上是一個索引器。但是,您不能在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); }
}
}
我以爲我們不能通過屬性返回數組? http://msdn.microsoft.com/en-us/library/0fss9skc%28v=VS.100%29.aspx忽略這一點,你回答了我的問題。 – Andrew 2011-05-24 13:25:55
@Andrew:*不能*和*不應該*不是一回事。你*可以*返回一個數組的引用 - 但是你無法控制數組的使用方式。 – 2011-05-24 13:27:24
我假設屬性實現應該讀取'return array [x,y];',而不是'return this [x,y];'(這會給出無限遞歸)。 – Douglas 2013-06-23 16:21:50
你的意思是這樣嗎?
array[x][y]
其中x是行而y是列。
也許這樣的事情?:
public string this[int x, int y]
{
get { return TextArray[x, y]; }
set { TextArray[x, y] = value; }
}
問題在於它處於靜態類中,因此必須是靜態成員。您不能在C#中創建靜態索引器。 – 2011-05-24 13:27:53
- 1. 在JavaScript 2D數組中設置對象的真/假屬性
- 2. C#數組屬性
- 3. XML屬性數組
- 4. NSManagedObject屬性數組
- 5. Hashset 2d數組
- 6. Javascript 2D數組
- 7. 2D Javascript數組
- 8. 將3d數組選擇性地整形爲2d數組
- 9. 在Unity 2D Text組件中,屬性fontSize的單位是?
- 10. StreamReader到2d數組
- 11. Numpy重組2D數組
- 12. 一個數組屬性
- 13. 屬性或數組 - PHP
- 14. WPF數組屬性綁定
- 15. 設置數組的屬性
- 16. 返回數組的屬性
- 17. 數組作爲類屬性?
- 18. Java數組:屬性大小?
- 19. 轉換XML屬性數組
- 20. 數組的XML屬性(PHP)
- 21. Phing中的數組屬性
- 22. 比較數組屬性
- 23. 標題屬性數組
- 24. SimpleXML屬性到數組
- 25. 將2D String數組轉換爲2D double
- 26. 遍歷angularjs指令2D陣列屬性
- 27. 將2d雙數組轉換爲2d int數組
- 28. Php 2d數組作爲C#2d數組/結構體
- 29. php 2d數組...將mysql結果存儲在2d數組中
- 30. 如何在2D中將2D數組投影到新數組中?
無法獲取您的問題,請精心製作 – 2011-05-24 13:20:40