C#-为什么我不能投射List< MyObject>继承自List< MyObject>的类? [英] C# - Why can I not cast a List<MyObject> to a class that inherits from List<MyObject>?

查看:93
本文介绍了C#-为什么我不能投射List< MyObject>继承自List< MyObject>的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,我将其称为MyObject。这是一个控制特定数据行的类。

I've got an object, which I'll call MyObject. It's a class that controls a particular data row.

然后我有了一个名为MyObjectCollection的集合类:

I've then got a collection class, called MyObjectCollection:

public class MyObjectCollection : List<MyObject> {}

为什么我不能执行以下操作:

Why can I not do the following:

List<MyObject> list = this.DoSomethingHere();
MyObjectCollection collection = (MyObjectCollection)list;

预先感谢。

编辑:错误是InvalidCastException

推荐答案

我的猜测是 DoSomethingHere 不返回 MyObjectCollection 的实例。

My guess is that DoSomethingHere doesn't return an instance of MyObjectCollection.

让我们在这里摆脱所有泛型等,因为它们不相关。这是我怀疑您要尝试执行的操作:

Let's get rid of all the generics etc here, as they're not relevant. Here's what I suspect you're trying to do:

public static object CreateAnObject()
{
    return new object();
}

object o = CreateAnObject();
string s = (string) o;

那会(在执行时)失败,这是很正确的。

That will fail (at execution time) and quite rightly so.

将其带回到您的代码中,除非 DoSomethingHere actually 返回 MyObjectCollection 在执行时,转换将失败。

To bring it back to your code, unless DoSomethingHere actually returns a MyObjectCollection at execution time, the cast will fail.

这篇关于C#-为什么我不能投射List&lt; MyObject&gt;继承自List&lt; MyObject&gt;的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆