C# InvalidCastException 尽管基类相同

标签 c# generics exception

以下代码抛出 InvalidCastException .

public static MachineProductCollection MachineProductsForMachine(
    MachineProductCollection MachineProductList, int MachineID)
{
    return (MachineProductCollection)
        MachineProductList.FindAll(c => c.MachineID == MachineID);
}

这让我感到惊讶,因为 MachineProductCollection 只是一个通用的 MachineProducts 列表,这正是 FindAll() 应该返回的。这是完整的 MachineProductCollection 源代码。您会注意到它只是 List 的包装器。

[Serializable]
public partial class MachineProductCollection :
        List<MachineProduct>
{
    public MachineProductCollection() { }
}

我采用了以下方法,它基本上循环遍历类型为 List 的 FindAll() 结果,并将每个项目添加到我的 MachineProductCollection 中。显然,我不喜欢所需的迭代。

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 吗?

最佳答案

是的,无效强制转换异常是正确的。您可以自由地从派生类强制转换为基类,但不能盲目地从基类强制转换为派生类,除非对象确实是派生类的实例。这与您不能这样做的原因相同:

object obj = new object();
string str = (string) obj;

对吧? objectstring 的基础,您不能随意将object 转换为string。另一方面,这会起作用,因为 obj 确实是一个字符串:

object obj = "foo";
string str = (string) obj;

关于C# InvalidCastException 尽管基类相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1117563/

相关文章:

c# - WPF:有没有办法进行内联格式化?

c# - 如何实现 ASP.Net 复合服务器控件的 ClientInstanceName 属性

Java 泛型,将 T 方法作为 T 而不是其父类(super class)调用

java - 如何使用 request-handler-advice-chain 和 ExpressionEvaluatingRequestHandlerAdvice?

c++ - 构造函数不抛出异常

java - 如果消费者线程遇到异常,如何停止生产者线程

c# - 从 EventLog.CreateEventSource 接收 "...has already been registered..."即使我正在检查 !EventLog.SourceExists

c# - Verlet Integration 正在炸毁我的物理引擎

Java - 类型转换、泛型、对象和数组

ios - 使用泛型类型的 Swift 工厂