我嘗試了下面的解決方案,但我不喜歡它。我正在尋找擴展類,而不是封裝double[]
。將Last屬性添加到System.Array的最佳方法是什麼?
謝謝。
編輯:我們需要.NET 2.0
public class DoubleArray : IList, ICloneable
{
protected double[] items;
/// <summary>
/// Gets the last item in the array.
/// </summary>
public double Last { get { return items[items.Length-1]; } }
/// <summary>
/// Gets the number of items in the array.
/// </summary>
public int Length { get { return items.Length; } }
/// <summary>
/// Number of items constructor.
/// </summary>
/// <param name="len">Number of items</param>
public DoubleArray(int len)
{
items = new double[len];
}
public double this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
public bool IsReadOnly
{
get { return items.IsReadOnly; }
}
public bool IsFixedSize
{
get { return items.IsFixedSize; }
}
public void CopyTo(Array array, int index)
{
items.CopyTo(array, index);
}
public IEnumerator GetEnumerator()
{
return items.GetEnumerator();
}
public object SyncRoot
{
get { return items.SyncRoot; }
}
public bool IsSynchronized
{
get { return items.IsSynchronized; }
}
object ICloneable.Clone()
{
return items.Clone();
}
#region ICollection and IList members implementation
// hides this members from intellisense, see: http://stackoverflow.com/questions/10110205/how-does-selectedlistviewitemcollection-implement-ilist-but-not-have-add
int ICollection.Count
{
get { return items.Length; }
}
int IList.Add(object value)
{
throw new NotImplementedException();
}
bool IList.Contains(object value)
{
throw new NotImplementedException();
}
void IList.Clear()
{
throw new NotImplementedException();
}
int IList.IndexOf(object value)
{
throw new NotImplementedException();
}
void IList.Insert(int index, object value)
{
throw new NotImplementedException();
}
void IList.Remove(object value)
{
throw new NotImplementedException();
}
void IList.RemoveAt(int index)
{
throw new NotImplementedException();
}
object IList.this[int index]
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
#endregion
}
作爲一個實現,我認爲這將是迄今爲止最簡單的解決方案。你還有什麼可以得到最後的財產?我想,你可以單獨追蹤最後一個值,方法是通過修改底層數組的所有方法來捕獲最後一個值,但這樣做的工作量太大或太少,無法獲得增益。這裏的實現可能與你將要使用數組給你的工作一樣好。 – Rup 2012-07-17 08:40:04
此方法的一個缺點是無法將DoubleArray類作爲參數傳遞給接受'double []'的方法。 – abenci 2012-07-17 09:42:39