为什么需要协方差接口(输出类型)? [英] Why do I need an Interface for Covariance (out Type)?

查看:100
本文介绍了为什么需要协方差接口(输出类型)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要再次使用协变 out 泛型类型修饰符。我有一个类的泛型类型,并希望添加 out ,但是VS告诉我这只能在接口上实现。



但为什么我只能在界面上使用 out 修饰符?



我帮助自己创建一个我的类的接口副本,但是这对我来说似乎有点奇怪,只有一个接口,所以我可以使用这个修饰符。

解决方案

<要确保类的定义实际上是协变的,这是非常困难的。编译器更容易确保接口实际上是协变的。



对于一个类,只需使用泛型类型的字段立即强制泛型参数是不变的,因为就编译器可以说的而言,该值可以被读取和修改。尽管类可以支持方差,但在实践中,需要向开发人员实际使用它的约束将非常困难,而不仅仅是创建一个包装接口。 / p>

让我们考虑一个简单的例子:

  public interface IWrapper< out T> ; 
{
T Value {get; }
}
public class Wrapper< T> :IWrapper< T>
{
public Wrapper(T value)
{
Value = value;
}
public T Value {get;私人设置; }

$


$ b

上面显示的类对于 T (直到您将其投射到界面)。它接受一个类型为 T 的输入值(通过构造函数)。只有因为构造函数没有通过接口暴露,接口才能够协变。


I just need to use the covariant out generic type modifier again. I had a class with a generic type and wanted to add an out but VS told me that this is only possible on interfaces.

But why can I use the out modifier only on an interface?

I helped myself in creating an interface copy of my class but this seems a little bit strange to me to only have an interface so I can use this modifier.

解决方案

It's extremely difficult to ensure that the class's definition is in fact covariant. It is much easier for the compiler to ensure that the interface is in fact covariant.

With a class, simply having a field that uses the generic type instantly forces the generic argument to be invariant, because as far as the compiler can tell, the value can be both read and modified. While it might be possible for classes to support variance, in practice the constraints that it would need to apply for developers to actually use it would be prohibitively difficult, much more so than simply creating a wrapping interface.

Let's consider a simple example:

public interface IWrapper<out T>
{
    T Value { get; }
}
public class Wrapper<T> : IWrapper<T>
{
    public Wrapper(T value)
    {
        Value = value;
    }
    public T Value { get; private set; }
}

The class shown above is not covariant with respect to T (until you cast it to the interface). It accepts an input value of type T (through the constructor). The interface is able to be covariant only because the constructor is not exposed through the interface.

这篇关于为什么需要协方差接口(输出类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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