ハウスクラスには、機能のコレクションがある場合があります。
基本的に、「Feature」と呼ばれる抽象基本クラスまたは「IFeature」と呼ばれるインターフェースを作成し、それを機能(つまりGarden
)となるクラスに継承/実装することができます。
House
次に、 「機能」というクラスでコレクションを作成するだけです。
C#のインターフェイスの例を次に示します。
interface IFeature
{
// Properties or methods you want all the features to have.
decimal Price { get; }
}
フィーチャクラスはIFeature
インターフェイスを実装する必要があります。
class Garden : IFeature
{
// This property is needed to implement IFeature interface.
public decimal Price { get; private set; }
public Garden(decimal price) { Price = price; }
}
を実装するIFeature
には、クラスにdecimal
「Price」というプロパティがGarden
あり、上記のクラスやPool
以下のクラスのようなgetアクセサーが必要です。
class Pool : IFeature
{
public decimal Price { get; private set; }
public float Depth { get; private set; }
public Pool(decimal price, float depth) { Price = price; Depth = depth; }
}
House
クラスには、またはのIFeature
代わりにのコレクションが必要です。Pool
Garden
class House
{
public List<IFeature> Features { get; private set; }
public House()
{
Features = new List<IFeature>();
}
}
次に、次のような機能を家に追加できます。
House h = new House();
h.Features.Add(new Garden(6248.12m));
h.Features.Add(new Pool(4830.24m, 10.4f));
そして、LINQを使用すると、次のことができます。
// Check whether the house has a garden:
h.Features.Any(f => f is Garden);
// Get the total cost of features.
h.Features.Sum(f => f.Price);
// Get the pools that are deeper than 5 feet.
h.Features.OfType<Pool>().Where(p => p.Depth > 5f);
// etc.
インターフェイスに関する詳細情報。
LINQに関する詳細情報。