다음 코드는 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() { }
}
나는 기본적으로 List 형태이며 내 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이 throw됩니다. 참조 변환은 하나의 참조 유형에서 다른 참조 유형으로의 변환입니다. 참조 유형을 변경할 수는 있지만 전환 목표의 유형이나 값은 절대 변경하지 않습니다. 한 유형에서 다른 유형으로 객체를 형변환하는 것은이 예외의 빈번한 원인입니다.
List가 MachineProductCollection의 기반임을 고려해 볼 때 실제로이 값이 InvalidCastException이되어야합니까?
위대한 답변 - 짧고 달콤한. 특히 객체/문자열 유추를 통해 이제는 완전히 이해가됩니다. 감사. –