次のコードはInvalidCastExceptionをスローします。C#InvalidCastException同じベースクラスですが
public static MachineProductCollection MachineProductsForMachine(
MachineProductCollection MachineProductList, int MachineID)
{
return (MachineProductCollection)
MachineProductList.FindAll(c => c.MachineID == MachineID);
}
MachineProductCollectionは、単にのfindAll()が返す必要があります正確に何であるMachineProductsの一般的なリストであるので、これは私を驚かせます。ここにMachineProductCollectionの完全なソースコードがあります。あなたは単にListのラッパーにすぎません。
[Serializable]
public partial class MachineProductCollection :
List<MachineProduct>
{
public MachineProductCollection() { }
}
私は基本的にタイプ一覧であり、私のMachineProductCollectionに各項目を追加のfindAll()の結果をループし次に頼っ。明らかに、私は必要な反復が気に入らない。
public static MachineProductCollection
MachineProductForMachine(MachineProductCollection
MachineProductList, int MachineID)
{
MachineProductCollection result =
new MachineProductCollection();
foreach (MachineProduct machineProduct in
MachineProductList.FindAll(c => c.MachineID == MachineID))
{
result.Add(machineProduct);
}
return result;
}
ドキュメントには、明示的な参照変換中にエラーが発生した場合にInvalidCastExceptionがスローされると記載されています。参照変換は、ある参照型から別の参照型への変換です。参照のタイプを変更する可能性はありますが、コンバージョンのターゲットのタイプや値は決して変更しません。オブジェクトの型をある型から別の型にキャストすることは、この例外の原因になることがよくあります。
ListがMachineProductCollectionのベースであることを考慮すると、これは本当にInvalidCastExceptionであるべきですか?
偉大な答え - 短いと甘い。これは、オブジェクト/文字列の類推によって特に完全に理解されます。ありがとう。 –