[英]Building an object with a [] interface ( not from ILIst) in c#
我想傳遞一個總是已知大小的數組中的一些值。 我想定義一個表示這個十進制值數組的類,它不能調整大小,總是具有相同數量的元素,並支持[]數組表示法。
在c ++中,我可以為此執行運算符重載 - 但我無法在c#中看到如何執行此操作
要清楚 - 類的使用將是這樣的:
MyValues values = new MyValues;
values[3] = 14;
values[7] = 10
.... 然后
decimal aValue = values[2];
建議?
你需要編寫一個索引器 ,如下所示:
public decimal this[int index] {
get { return data[index]; }
set { data[index] = value; }
}
使用索引器
public class MyValues {
private readonly decimal[] numbers = new decimal[10];
public decimal this[int index] {
get { return numbers[index]; }
set { numbers[index] = value; }
}
}
您可能希望添加一些邊界檢查以提供更好的故障消息。 您可能也不想硬編碼數組大小。
使用索引器 ,您可以編寫一個簡單的泛型類,如:
public class FixedArray<T>
{
private T[] array;
public int Length { get { return array.Length; } }
public FixedArray (int size)
{
array = new T[size];
}
public T this[int index]
{
get { return array[index]; }
set { array[index] = value; }
}
}
就像是:
decimal this[int ind]
{
get
{
return array[ind];
}
set
{
array[ind] = value;
}
}
嘗試ReadOnlyCollection類。 還要注意數組的危險, 這里的文章真的很好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.