繁体   English   中英

无法将受约束的通用接口引用转换为协变接口引用

[英]Unable to cast constrained generic interface reference to covariant interface reference

我试图了解协方差如何与泛型类型约束一起工作,并且似乎没有明显的原因忽略了约束。

考虑以下代码:

    public interface IContainer<out T> { }

    public interface IContents { }

    public class Food : IContents { }

    public class Foo
    {
        public void Bar<T>() where T : IContents
        {
            IContainer<IContents> x = null;
            IContainer<T> y = null;
            IContainer<Food> z = null;
            x = y; // Cannot convert source type 'IContainer<T>' to target type 'IContainer<IContents>'
            x = z; // Valid
        }
    }

为什么编译器会在x = y上产生“无法转换”错误而在x = z上没有产生错误?

C# 不支持值类型的变体 - 来自变体泛型接口文档

C# 中的refinout参数不能是变体。 值类型也不支持方差

即下一个将不起作用:

public struct MyStruct : IContents
{
}

var structContainer = (IContainer<MyStruct>)null;
IContainer<IContents> x = structContainer;

由于T既不受class也不受struct限制,它可以是引用类型或值类型,所以在一般情况下IContainer<T>不能分配给IContainer<IContents>

Bar方法添加class约束:

public class Foo
{
    public void Bar<T>() where T : class, IContents
    {
        IContainer<IContents> x = null;
        IContainer<T> y = null;
        IContainer<Food> z = null;
        x = y; // Now Valid
        x = z; // Valid
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM