为什么不编译以下内容?(涉及C#中的泛型和继承) [英] Why does the following doesn't compile? (involves generics and inheritance in c#)

查看:48
本文介绍了为什么不编译以下内容?(涉及C#中的泛型和继承)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译如下:

This compiles:

    class ReplicatedBaseType
    {
    }

    class NewType: ReplicatedBaseType
    {
    }

    class Document
    {
    ReplicatedBaseType BaseObject;

    Document()
    {
     BaseObject = new NewType();
    }
}

但这不是:

    class DalBase<T> : where T: ReplicatedBaseType
    {
    }

    class DocumentTemplate
    {
    DalBase<ReplicatedBaseType> BaseCollection;
    DocumentTemplate ()
    {
    BaseCollection= new DalBase<NewType>(); // Error in this line. It seems this is not possible
    }
    }

这是什么原因?

推荐答案

针对.NET 4的C#4.0中存在差异,但仅限于 in / out (哦,还有引用类型的数组).例如,要创建协变序列:

Variance exists in C# 4.0 targetting .NET 4), but is limited to interfaces and usage of in/out (oh, and arrays of reference-types). For example, to make a covariant sequence:

class DalBase<T> : IEnumerable<T> where T: ReplicatedBaseType
{
    public IEnumerator<T> GetEnumerator() {throw new NotImplementedException();}
    IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}

class DocumentTemplate
{
    IEnumerable<ReplicatedBaseType> BaseCollection;
    DocumentTemplate()
    {
        BaseCollection = new DalBase<NewType>(); // Error in this line. It seems this is not possible
    }
}

但除此之外...不.坚持使用非通用列表( IList ),或使用预期的列表类型.

But other than that... no. Stick to either non-generic lists (IList), or use the expected list type.

这篇关于为什么不编译以下内容?(涉及C#中的泛型和继承)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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