简体   繁体   中英

Action Generics from Base Type

I would like an IEnumerable<Action<T>> subscriptions which is an array of actions, each with a different type parameter - I would like to pass a list in to a service constructor to loop through these and register but the compiler complains (not surprisingly).

Is there any way to achieve the ability to pass in a base type which has a derived specific implementation, and loop through the list?

class InternalBusService
{
    private InternalBus bus;

    public InternalBusService(IEnumerable<Action<T>> subscriptions)
    {
        foreach (var subscription in subscriptions)
        {
            this.bus.Subscribe<T>(subscription);
        }
    }
}

Do you mean like this?

class InternalBusService<T>
    where T : SomeType
{
    public InternalBusService(IEnumerable<Action<T>> subscriptions)
    {
        foreach (var subscription in subscriptions)
        {
            this.bus.Subscribe<T>(subscription);
        }
    }
}

where T : SomeType can be any type that you want to restrict T to.

If I understand that you want to pass in IEnumerable<Action<T>> where T for each action in the enumerable is NOT the same type, that isn't possible the way you are doing it.

Perhaps you could do something like this "concept code" below (meaning its just to show you what I'm thinking, it isn't necessarily a solution).

public interface IActionWrapper
{

    bool AcceptsParameterType(Type t);
    void PerformAction(object o);
}

public class ActionWrapper<T> : IActionWrapper
{
    Action<T> yourAction {get;set;}

    public bool AcceptsParameterType(Type t)
{
return t is T;
}

public void PerformAction(object o)
{
  yourAction((T)o);
}

}

Then you could pass IEnumerable<IActionWrapper>> into your function which isn't generic-typed and would support multiple types by its implementation.

To solve compiler error:

class InternalBusService<T>
{
    public InternalBusService(IEnumerable<Action<T>> subscriptions) { }
}

But not sure that it's what you're trying to achieve actually.

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