c# - 协变/逆变 : how to make the following code compile

标签 c# generics c#-4.0 covariance

更新:以下代码仅在 C#4.0 (Visual Studio 2010) 中有意义

看来我对协变/逆变有一些误解。谁能告诉我为什么以下代码无法编译?

public class TestOne<TBase>
{
    public IEnumerable<TBase> Method<TDerived>(IEnumerable<TDerived> values)
        where TDerived: TBase
    {
        return values;
    }
}

编译时:(!!!)

public interface IBase
{
}
public interface IDerived: IBase
{
}
public class TestTwo
{
    public IEnumerable<IBase> Method(IEnumerable<IDerived> values)
    {
        return values;
    }
}

最佳答案

协变仅适用于引用类型(对于类型参数),因此您必须添加类约束:

public IEnumerable<TBase> Method<TDerived>(IEnumerable<TDerived> values)
    where TDerived : class, TBase
{
    return values;
}

这将阻止您尝试转换,例如 IEnumerable<int>进入 IEnumerable<object> , 这是无效的。

关于c# - 协变/逆变 : how to make the following code compile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9363699/

相关文章:

scala - 用于无形 Hlist 的通用 Poly2 文件夹案例

c# - 使用 lambda 表达式参数调用泛型方法的反射

c# - 如何避免 Code Contracts 语句中的代码重复

c# - .NET Core 中 Assembly.GetEntryAssembly() 的等价物是什么?

c# - 是否有等效于 IsDebuggerPresent() 的 C#?

c# - C#存储对List <T>的引用

.net - 如果 Windows 服务在停止时不退出线程会发生什么?

java - 无法在 Unity3D 中调用 native Android 代码

c# - LINQ - GroupBy 一个键,然后将每个分组的项目放入单独的 'buckets'

c# - 亚马逊 MWS API :Retrieve multiple Images uploaded by Seller c#