对于具有“集合”性质的类(例如您的例程),
若您打算使用类进行封装,
下述主要讲述一种创建这一类“集合”性质的类的封装思想,仅供参考,
若您对这种封装思想感觉不喜欢或者觉得麻烦(事实上并不麻烦),
仍然可以坚持自己的方法。
1. 实现单位实体:
/// <summary>
/// 订单信息类
/// </summary>
public class OrderInfo
{
public OrderInfo() { }
/// <summary>
/// 创建新的订单信息
/// </summary>
/// <param name="manufacturerId">厂商ID</param>
/// <param name="number">件号</param>
/// <param name="amount">数量</param>
public OrderInfo( string manufacturerId, string number, int amount )
{
_manufacturerId = manufacturerId;
_number = number;
_amount = amount;
}
/// <summary>
/// 厂商ID
/// </summary>
private string _manufacturerId;
public string ManufacturerID
{
get { return _manufacturerId; }
set { _manufacturerId = value; }
}
/// <summary>
/// 件号
/// </summary>
private string _number;
public string Number
{
get { return _number; }
set { _number = value; }
}
/// <summary>
/// 数量
/// </summary>
private int _amount;
public int Amount
{
get { return _amount; }
set { _amount = value; }
}
}
2. 实现订单集合类
/// <summary>
/// 订单集合类(实现 ICollection 接口,所以可以使用该类的对象作为数据源)
/// </summary>
public class OrderInfoCollection : ICollection<OrderInfo>
{
private List<OrderInfo> items = new List<OrderInfo>();
public OrderInfo this[int index]
{
get
{
return items[index];
}
}
#region ICollection<OrderInfo> 成员
public void Add( OrderInfo item )
{
items.Add(item);
}
public void Clear()
{
items.Clear();
}
public bool Contains( OrderInfo item )
{
return items.Contains(item);
}
public void CopyTo( OrderInfo[] array, int arrayIndex )
{
items.CopyTo(array, arrayIndex);
}
public int Count
{
get { return items.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove( OrderInfo item )
{
return items.Remove(item);
}
#endregion
#region IEnumerable<OrderInfo> 成员
public IEnumerator<OrderInfo> GetEnumerator()
{
foreach ( OrderInfo var in items )
{
yield return var;
}
}
#endregion
#region IEnumerable 成员
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
3. 实现订单类
/// <summary>
/// 订单类
/// </summary>
public class Orders
{
private OrderInfoCollection items;
public OrderInfoCollection Items
{
get { return items; }
set { items = value; }
}
}