繁体   English   中英

回报类型的差异

[英]Variance in return type

编辑:也许这是一个更清晰的问题,更多的是问题的重点:

在一些通用接口IInterface<T> ,我想返回一个泛型类型的对象,其中一个类型参数应该是IInterface<T>

public class OtherType<T> {}
public interface IInterface<T>
{
    OtherType<IInterface<T>> Operation();
}
public class Impl : IInterface<int>
{
    public OtherType<IInterface<int>> Operation()
    {
        return new OtherType<Impl>();
    }
}

由于Impl实现了IInterface<int> ,因此我可以通过这种方式使用它。 然而,似乎我不能,我得到编译器错误

无法将表达式类型OtherType<Impl>转换为返回类型OtherType<IInterface<int>>

OtherType<IInterface<int>>并不意味着“implements” - 它的意思是“是一个带有泛型类型参数Interface<int> OtherType类型,但这不是你怎么说的。

如果您只是想确保返回类型实现IInterface<int>那么将其设置为返回类型:

public interface IInterface<T>
{
    IInterface<T> Operation();
}

public class Impl : IInterface<int>
{
    public <IInterface<int>> Operation()
    {
        return new OtherType();
    }
}

哪里

public class OtherType : IInterface<int>
{}

这意味着您可以返回任何实现IInterface<int>

否则,您可以在调用使用泛型类型约束时使其更受限制:

public interface IInterface<T>
{
    TRet Operation<TRet>() where TRet : IInterface<T>;
}

public class Impl : IInterface<int>
{
    public TRet Operation<TRet>() where TRet : IInterface<int>
    {
        return new OtherType();
    }
}

这意味着您可以约束操作以返回特定的类,而该类又实现了IInterface<int>

它将被称为:

Impl i = new Impl();
OtherType x = i.Operation<OtherType>();

问题是OtherType<T>是一个类,泛型类不允许C#中的共同/逆转。 通用interfaces做,只要out类型不会在任何输入位置出现,而in类型不会出现在任何输出位置。 在您的代码示例中,您可以通过引入标记为covariant的附加接口,然后更改返回类型来进行编译。

public interface IOtherType<out T> {} // new
public class OtherType<T> : IOtherType<T> { }

public interface IInterface<T>
{
    IOtherType<IInterface<T>> Operation(); // altered
}
public class Impl : IInterface<int>
{
    public IOtherType<IInterface<int>> Operation()
    {
        return new OtherType<Impl>();
    }
}

考虑到代码片段中的细节有限,这是否真的适合您的用例以及其他方法定义,这是您可以知道的。

暂无
暂无

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

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