c# - C# 中的继承 - 简单问题

标签 c# generics inheritance covariance

Duplicate

In C#, why can’t a List object be stored in a List variable

这是我的代码:

public class Base
    {
        protected BindingList<SampleBase> m_samples;

        public Base() { }
    }

    public class Derived : Base
    {
        public Derived()
        {
            m_samples = new BindingList<SampleDerived>();
        }
    }

SampleDerived 派生自 SampleBase

按照继承逻辑,我应该可以做到这一点。但是,它无法编译 - 错误表明 SampleBase 无法隐式转换为 SampleDerived 类型。给了什么?

我正在使用 C# 2.0

最佳答案

您正在尝试使用 C# 3.0 及更早版本不支持的协方差(但将在 C# 4.0 中提供)。您仍然可以添加 SampleDerived 类型的对象进入m_samples , 但列表的通用类型需要是 SampleBase .

编辑: 所以 Pavel 是对的,C# 4.0 实际上对此没有帮助。如果 m_sample被定义为 IBindingList<SampleBase>使用(虚构的)协变接口(interface) IBindingList<out T> .

关于c# - C# 中的继承 - 简单问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1180569/

相关文章:

c++ - C++中的继承

java - 扩展 JPanel 的问题

c# - GC 启动和停止事件

c# - 异步保证什么?

generics - 使用泛型类型构造对象?

c# - Java 泛型与 C# where 关键字

java - 如何实现 Java 泛型

c# - 即使使用 [BindProperty(SupportsGet = true)],Razor 页面也不会在 POST 上绑定(bind)属性

c# - 如何在 C# 中创建不可变对象(immutable对象)?

c# - EF Code First - 热切加载和过滤子类属性(继承)