繁体   English   中英

C# 泛型类型中的协方差

[英]C# Covariance in generic types

对于这个简单的示例,我无法绕过 C# 协方差,这是我定义 model 的方式:

interface IResponse { }
interface ICommand<out TResponse> where TResponse : IResponse { }
class Response : IResponse { }
class Command<TResponse> : ICommand<TResponse> where TResponse : IResponse { }

所以我可以像这样使用它

IResponse rsp = new Response(); //Works, obviously!
ICommand<IResponse> cmdi = new Command<Response>(); //Works, but I don't need this 
Command<IResponse> cmd = new Command<Response>(); //Compile time error! :(

Command Command<TResponse>中的 Command 甚至没有任何TResponse类型的属性或方法。 我该如何更改它以使其正常工作?

出现编译时问题,因为您声明了 Command 以便它只能接收 TResponse,而不是 IResponse。

考虑改进你的代码,而不是

class Command<TResponse>

利用

class Command<IResponse>. 

Command 现在将与任何实现 IResponse 的 TResponseXYZ 类型一起工作,就像您想要的那样。 为了确保 Command 方法可以访问 TResponseXYZ 类型的所有相关属性,您应该将它们发布为 TResponseXYZ 中的公共属性,并使用 IResponse 接口将它们声明为 get;set; 特性。 制定的例子:

interface ICommand<out TResponse> where TResponse : IResponse { }

public interface IResponse
{
    int MyField { get; set; }
}

public class TResponseA : IResponse
{
    public int MyField { get; set; }
}

public class TResponseB : IResponse
{
    public int MyField { get; set; }
}

public class Command<TResponse> : ICommand<TResponse> where TResponse : IResponse
{
    public Command(IResponse R)
    {
        // here you can access R.MyField=17 using R.MyField
    }

    public static void Test()
    {
        var rA = new TResponseA() { MyField = 17 };
        var cmdA = new Command<TResponseA>(rA);

        var rB = new TResponseB() { MyField = 17 };
        var cmdB = new Command<TResponseB>(rB);
    }
}

暂无
暂无

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

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