简体   繁体   English

如何实现非通用接口并使用通用进行调用

[英]How to implement a non-generic interface and call with generic

Probably a bad title, but I am trying to abstract away the type "EventHub" from my generic Handler class. 可能是一个不好的标题,但我试图从通用Handler类中抽象出类型“ EventHub”。

I would like to inject a function instead into my subscribe method to decouple the two types. 我想将一个函数注入到我的订阅方法中,以分离这两种类型。 Unfortunately, the only way I can see doing this is if I make my IHandler a generic, but this causes other problems. 不幸的是,我看到的唯一方法是将IHandler设为通用,但这会导致其他问题。

Is there a design pattern to decouple these two types? 是否存在将这两种类型分离的设计模式? Commented out are lines that I would like in some way. 我想以某种方式注释掉的行。

public interface IHandler
{
    //void Subscribe(Func<Action<T>, Guid> subscribe);
    void Subscribe(EventHub eventHub);
    void Unsubscribe(Action<Guid> action);
}

public abstract class Handler<T> : IHandler
{
    private Guid _subscriptionToken;

    public virtual void Subscribe(EventHub eventHub)
    {
        var action = new Action<T>(Handle);
        _subscriptionToken = eventHub.Subscribe(action);
    }

    /*public virtual void Subscribe(Func<Action<T>, Guid> subscribe)
    {
        var action = new Action<T>(Handle);
        _subscriptionToken = subscribe(action);
    }*/

    public virtual void Unsubscribe(Action<Guid> action)
    {
        action(_subscriptionToken);
    }

    public abstract void Handle(T eventType);
}

Thanks for the help! 谢谢您的帮助!

internal interface IHandler
{
    void Subscribe(Func<Action<object>, Guid> subscribe);
    void Unsubscribe(Action<Guid> action);
}

public abstract class Handler<T> : IHandler
{
    private Guid _subscriptionToken;

    public virtual void Subscribe(Func<Action<object>, Guid> subscribe)
    {
        var action = new Action<T>(HandleNonAsync);
        _subscriptionToken = subscribe(Convert(action));
    }

    public virtual void Unsubscribe(Action<Guid> action)
    {
        action(_subscriptionToken);
    }

    public abstract Task HandleAsync(T eventType);

    private void HandleNonAsync(T eventType)
    {
        HandleAsync(eventType).GetAwaiter().GetResult();
    }

    private Action<object> Convert(Action<T> myActionT)
    {
        if (myActionT == null) return null;
        else return new Action<object>(o => myActionT((T)o));
    }
}

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

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