基本的に私はそれらのサンプルクラスを手に入れました:
public interface IHasParts<TCollectionType> : where TCollectionType : ICollection
{
TCollectionType Parts { get; set; }
}
public class CarPart
{
//...
}
public class Car : IHasParts<List<CarPart>>
{
public List<CarPart> Parts { get; set; }
//...
}
はい、ICollection
IHasPartsを実装するクラスはParts
、いくつかのハードプログラムされた条件に基づいて異なるリストタイプを必要とするため、ここの汎用インターフェイスを使用する必要があります。
今、私はieの未知のオブジェクトを取得し、Car
それをまだParts
利用可能なプロパティを持っている最も高い親にキャストする必要があります。
Car c = new Car() {
Parts = new List<CarPart>() {
// ...
}
};
object o = (object)c;
int partsCount = ((IHasParts<ICollection>)o).Parts.Count; // InvalidCastException
どうやってやるの?DotNetFiddle
のICollection
代わりにCarクラスを定義するとList<CarPart>
、次のように機能します。
public class Car : IHasParts<ICollection>
{
public ICollection Parts { get; set; }
}
あなたはまだあなたのパーツを初期化することができます List<CarPart>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加