简体   繁体   中英

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.

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 . To do this, make the type argument a part of the base class , not the method:

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) 
    { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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