简体   繁体   English

与类型为T的泛型的协方差

[英]Covariance with generics where type T is a

I need a child class to implement a method that returns a Type T, where T meets certain criteria as follows: 我需要一个子类来实现返回类型T的方法,其中T满足以下特定条件:

public abstract class NavEntityController<ChildEntity, GenericNavService_T_Entity ...>
  where ChildEntity : NavObservableEntity<GenericNavService_T_Entity>
{
   public abstract T ReadAll<T>(bool forceUpdate = false) where T : NavObservableCollection<ChildEntity>;
   //others
}

I'm trying to implement this as follows in the concrete class: 我正在尝试在具体的类中实现以下目标:

public class NavJobController : NavEntityController<NavObservableJob, JobCard_Service, JobCard>
    {
       public override NavObservableCollection<NavObservableJob> ReadAll(bool forceUpdate = false)
       {
                //...
       }

}

public class NavObservableJob : ...  {} //Let's just say this is a class or we are going to go down a whole tree of dependencies

But I get the error that my "child class does not implement inherited abstract member ReadAll from the parent". 但是我得到一个错误,即我的“子类未实现从父类继承的抽象成员ReadAll”。

A concrete implementation of an abstract class needs to implement the abstract members of the abstract class. 抽象类的具体实现需要实现抽象类的抽象成员。

If you have a generic abstract member then you need a generic concrete implementation. 如果您有通用的抽象成员,则需要通用的具体实现。

NavObservableJob is more specialized and specific than any NavObservableCollection<ChildEntity> implementation, since NavObservableCollection<T> is not covariant. NavObservableJob是更专门和比任何特定NavObservableCollection<ChildEntity>实施方式中,因为NavObservableCollection<T>是不协变。


To achieve what you want, you need to define NavObservableCollection<T> as an interface. 要实现所需的功能,需要将NavObservableCollection<T>定义为接口。 This will allow you to define the interface as covariant, eg 这将允许您将接口定义为协变,例如

public interface INavObservableCollection<out T>
{
   // ...
}

Note: The use of the out Generic Modifier . 注意:使用out通用修饰符

Then change NavObservableCollection<T> so that it implements the new interface, 然后更改NavObservableCollection<T> ,以实现新接口,

class NavObservableCollection<T> : INavObservableCollection<T>
{
    // ...
}

Then use the interface as your generic constraint, 然后将接口用作通用约束,

public abstract class NavEntityController<ChildEntity, GenericNavService_T_Entity>
        where ChildEntity : NavObservableEntity<GenericNavService_T_Entity>
{
    public abstract T ReadAll<T>(bool forceUpdate = false)
            where T : INavObservableCollection<ChildEntity>;

    //others
}

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

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