协方差在C#泛型类 [英] Covariance in C# generic class

查看:259
本文介绍了协方差在C#泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#4.0 .NET 4.5的Silverlight 5
这似乎不可思议,我不能找到解决方案,因此需要一些帮助,请。

C# 4.0 .NET 4.5 Silverlight 5 It seems weird that I cant find the solution so need some help please.

我有基类基地和派生类儿童:基础。我有泛型类型做具体工作1 EF实体助手也是辅助类,其中T:EntityObject

I have base class Base and derived class Child : Base. I have also helper class which has generic type to do specific work one EF entities Helper where T : EntityObject.

孩子不具体工作与特定的实体myEntity所。EntityObject

Child does specific work with a specific entity MyEntity : EntityObject.

所以,我想:

public class Base
{
    protected Helper<EntityObject> helper;
}
public class Child : Base
{
    public Child()
    {
        helper = new Helper<MyEntity>();
    }
}



我希望有更多的派生类必须了解更多具体的泛型参数,我想这就是协方差...但还是不行...

I would expect that more derived class must know about more specific generic parameter and I think that's what covariance for... But that doesn't work...

什么是正确的方式来设计类这样?

What's the 'correct' way to design class like that?

编辑:对不起,我没能100%的清楚为什么不能我实现我所需要的。

sorry I didn't make it 100% clear why cant I achieve what I need.

。与一般的基本解决方案不起作用,因为基本的用户不知道的T类。想象一下:

a. Solution with generic Base doesn't work because user of the Base doesn't know the T type. Imagine:

public class User
{
    private Base<T> base; // this will not compile.
    public User(TypeEnum t)
    {
        if(t == TypeEnum.MyEntity) base = new Child();
...



乙。与接口解决方案不起作用,因为辅助使用牛逼无处不在(这是它的正确的目的是什么?)。想象一下,它有法

b. Solution with Interface doesn't work because helper uses T everywhere (it is its purpose right?). Imagine it has method

public IEnumerable<T> Process(IEnumerable<T> items) { return items; }



我如何把它在不知道什么牛逼接口

How do I bring it up in the interface which doesn't know anything about T

推荐答案

如果酒吧,这并不意味着部分<富> 部分<酒吧GT; 。有这样做你想要什么有两种方式。首先是制造基地型通用这样:

If Foo : Bar, that doesn't mean that Some<Foo> : Some<Bar>. There are two ways of doing what you want. The first is to make the base-type generic such that:

Base<T> where T : EntityObject {
    protected Helper<T> helper;
}
Child : Base<MyEntity> {...}



第二个是在基础类型为使用非通用接口,即有

The second is to use a non-generic interface at the base-type, i.e. have

Base {
    protected IHelper helper;
}
Child : Base {...}



其中后者情况下,助手< T> :IHelper ,对于一些非通用 IHelper 待定义

where in the latter case, Helper<T> : IHelper, for some non-generic IHelper to-be-defined.

作为一个侧面说明,你的可能的发现很容易向下传递值在构造函数,而不是使用保护字段。

As a side-note, you might find it easier to pass the value down in the constructor rather than using a protected field.

这篇关于协方差在C#泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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