基于IEnumerable的派生列表

基于IEnumerable的派生列表

本文介绍了基于IEnumerable的派生列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有在.NET Framework 4.0及更高版本中编译的以下代码:

I have the following code that compiles in .NET Framework version 4.0 and above:

public abstract class MyBase { }
public class MyDerived : MyBase { }

public abstract class MyBaseCollection<T> : IList<T> where T : MyBase
{
    protected readonly IList<T> deriveds = new List<T>();

    public void Test()
    {
        // This line works in .NET versions 4.0 and above, but not in versions below.
        IEnumerable<MyBase> bases = deriveds;
    }

    #region IList members with NotImplementedException
    // ...
    #endregion
}
public class MyDerivedCollection : MyBaseCollection<MyDerived> { }

但是在低于4.0的.NET Framework中,我在下一行得到了编译错误:

But in .NET Framework below 4.0 I get a compile error on the following line:

IEnumerable<MyBase> bases = deriveds;

问题是在.NET 4.0中对此进行了哪些更改(或已引入)?
是否有任何相关文档?

Question is what has changed (or was introduced) in .NET 4.0 regarding this?
Is there any documentation about this?

推荐答案

在.Net 4.0中,IEnumerable<T>接口已从以下位置更改:

In .Net 4.0 the IEnumerable<T> interface was changed from:

public interface IEnumerable<T>

public interface IEnumerable<T>

public interface IEnumerable<out T>

Topublic interface IEnumerable<out T>

请注意,单词out已添加到泛型类型参数中.这意味着泛型参数是协变的,这意味着您可以传递更多派生的类型.

Notice that the word out has been added to the generic type parameter. This means that the generic parameter is co-variant which means you can pass in a more derived type.

有关更多信息,请参见 msdn 信息

See msdn for more information

这篇关于基于IEnumerable的派生列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 05:48