简体   繁体   English

基础/派生类型泛型参数

[英]Base / Derived Type Generics Parameter

I'd like to have an abstract method inside an abstract class and method signature like this: 我想在抽象类和方法签名中有一个抽象方法,如下所示:

public abstract IEnumerable<SynchronizeItem<IDataItem>> Sync(IEnumerable<SynchronizeItem<IDataItem>> clientSyncItems);

In the derived class I want to define the method type safety: 在派生类中,我想定义方法类型安全性:

public override IEnumerable<SynchronizeItem<AdItem>> Sync(IEnumerable<SynchronizeItem<AdItem>> clientSyncItems)
{
    // Do something with the AdItems
    _adHandler.Foo(clientItems):
}

This is not possible. 这是不可能的。 Any other possibilities to achieve the same behavior? 任何其他可能实现相同的行为? I don't want to cast each usage of IDataItem to it's specific implementation within AdHandler class. 我不想将IDataItem的每个用法转换为它在AdHandler类中的特定实现。

Try to define your abstract method like: 尝试定义您的抽象方法,如:

public  IEnumerable<SynchronizeItem<T>> Sync<T>(IEnumerable<SynchronizeItem<T>> clientSyncItems)  where T : IDataItem;

Your other method, the implementation, is correct. 你的其他方法,实现,是正确的。

Renen's answer will not do quite what you want, as it appears to me you want the subclass to define the concrete type, not the caller . Renen的答案不会达到您想要的效果,因为在我看来,您希望子类定义具体类型,而不是调用者 To do this, make the type argument a part of the base class , not the method: 为此,请将type参数作为基类的一部分,而不是方法:

public class Base<T> where T : IDataItem
{
    public abstract IEnumerable<SynchronizeItem<T>> Sync(
        IEnumerable<SynchronizeItem<IDataItem>> 
        clientSyncItems);
}

And your derived class: 你的派生类:

public class Derived : Base<AdItem>
{
    public override IEnumerable<SynchronizeItem<AdItem>> Sync(
        IEnumerable<SynchronizeItem<AdItem>> 
        clientSyncItems) 
    { ... }
}

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

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