Why do I need an Interface for Covariance (out Type)?

时光总嘲笑我的痴心妄想 提交于 2019-12-20 02:59:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23480144/why-do-i-need-an-interface-for-covariance-out-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!