A、B、C が Basket オブジェクトに格納するアイテムであると仮定すると、これらのアイテムの基底クラスを作成し、ジェネリック コレクションを基底クラスのコレクションとして宣言する必要があります。
public interface IBasketItem
{
/* put some common properties and methods here */
public decimal Price { get; set; }
public string Name { get; set; }
}
public class A : IBasketItem
{ /* A fields */ }
public class B : IBasketItem
{ /* B fields */ }
public class C : IBasketItem
{ /* C fields */ }
public class Basket
{
private List<IBasketItem> _items = new List<IBasketItem>();
public void Add(IBasketItem item)
{
_items.Add(item);
}
public IBasketItem Get(string name)
{
// find and return an item
}
}
その後、 Basket クラスを使用してすべてのアイテムを保存できます。
Basket basket = new Basket();
A item1 = new A();
B item2 = new B();
C item3 = new C();
basket.Add(item1);
basket.Add(item2);
basket.Add(item3);
ただし、アイテムを取得するときは、共通のインターフェイスを使用するか、オブジェクトが実際にどのタイプであるかを知っておく必要があります。例えば:
IBasketItem myItem = basket.Get("cheese");
Console.WriteLine(myItem.Name);
// Take care, if you can't be 100% sure of which type returned item will be
// don't cast. If you cast to a wrong type, your application will crash.
A myOtherItem = (A)basket.Get("milk");
Console.WriteLine(myOtherItem.ExpiryDate);