我可以使用具体方法订阅通用 Action 吗?

Can I subscribe to a generic Action with a concrete method?


我有一个正在注册的通用 Action,然后转换为我期望的类型:

public interface IMyInterface { }

public static Action<IMyInterface> MyAction;

public class MyClass : IMyInterface { }

public void Subscribe()
{
    MyAction<MyClass> += MyMethod;
}

public void MyMethod(IMyInterface myInterface)
{
    var myClass = (MyClass)myInterface;
}

但我希望能够使用已经指定类型的方法进行订阅,这样我就可以避免额外的强制转换步骤。是否可以只订阅 MyActions 以便 IMyInterface 具有特定类型?这样 MyMethod 就可以变成这样:

public void MyMethod(MyClass myClass)
{

}

我尝试这样做的原因是因为我正在编写一个使用特定类型的消息传递系统。我正在使用泛型来确定要订阅哪些消息。我认为这部分不会影响我的问题,但它看起来像这样:

private Dictionary<Type, List<Action<IMessage>> subscribers = new Dictionary<Type, List<Action<IMessage>>();

public void SubscribeMessage<TMessage>(Action<IMessage> callback)
    where TMessage : IMessage
{
    var type = typeof(TMessage);
    if (subscribers.ContainsKey(type))
    {
        if (!subscribers[type].Contains(callback))
        {
            subscribers[type].Add(callback);
        }
        else
        {
            LogManager.LogError($"Failed to subscribe to {type} with {callback}, because it is already subscribed!");
        }
    }
    else
    {
        subscribers.Add(type, new List<Action<IMessage>>());
        subscribers[type].Add(callback);
    }
}

public void UnsubscribeMessage<TMessage>(Action<IMessage> callback)
    where TMessage : IMessage
{
    var type = typeof(TMessage);
    if (subscribers.ContainsKey(type))
    {
        if (subscribers[type].Contains(callback))
        {
            subscribers[type].Remove(callback);
        }
        else
        {
            LogManager.LogError($"Failed to unsubscribe from {type} with {callback}, because there is no subscription of that type ({type})!");
        }
    }
    else
    {
        LogManager.LogError($"Failed to unsubscribe from {type} with {callback}, because there is no subscription of that type ({type})!");
    }
}

//The use case given MyClass implements IMessage
public void Subscribe()
{
    SubscribeMessage<MyClass>(MyMethod);
}

public void MyMethod(IMessage myMessage)
{
    var myClass = (MyClass)myMessage;
}

那么我可以使用具有具体类型的方法订阅泛型 Action 吗?

您问题中的类型似乎有点乱码 - IMyInterface 在问题的顶部,IMessage 在底部。我假设了这些接口和基本方法:

public interface IMessage { }

public class MyClass1 : IMessage { }
public class MyClass2 : IMessage { }

public void MyMethod1(MyClass1 myClass1)
{
    Console.WriteLine("MyMethod1");
}

public void MyMethod2(MyClass2 myClass1)
{
    Console.WriteLine("MyMethod2");
}

现在,我进一步简化了您的代码,使其没有 SubscribeMessageUnsubscribeMessage 方法,因为这将迫使您保留对原始委托的引用以删除委托。使用一个 Subscribe 方法比 returns 一个 IDisposable 方法更容易取消订阅。与许多不同类型的代表相比,容纳一堆一次性用品要容易得多 - 否则就是“出锅入火”之类的事情。

这就是 Subscribe 所需的一切:

private Dictionary<Type, List<Delegate>> _subscribers = new Dictionary<Type, List<Delegate>>();

public IDisposable Subscribe<TMessage>(Action<TMessage> callback) where TMessage : IMessage
{
    var type = typeof(TMessage);
    if (!_subscribers.ContainsKey(type))
    {
        _subscribers.Add(type, new List<Delegate>());
    }
    _subscribers[type].Add(callback);
    return new ActionDisposable(() => _subscribers[type].Remove(callback));
}

我不再需要检查重复项。这应该是调用代码的责任。在某些情况下,两次调用委托可能是有效的。将它留给调用代码,以确保它是否是明智的做法。

我还使用了 List<Delegate>,因为它可以存储任何委托类型。

这是您需要的 ActionDisposable class:

public sealed class ActionDisposable : IDisposable
{
    private readonly Action _action;
    private int _disposed;

    public ActionDisposable(Action action)
    {
        _action = action;
    }

    public void Dispose()
    {
        if (Interlocked.Exchange(ref _disposed, 1) == 0)
        {
            _action();
        }
    }
}

现在是Send

public void Send<TMessage>(TMessage message) where TMessage : IMessage
{
    var type = typeof(TMessage);
    if (_subscribers.ContainsKey(type))
    {
        var subscriptions = _subscribers[type].Cast<Action<TMessage>>().ToArray();
        foreach (var subscription in subscriptions)
        {
            subscription(message);
        }
    }
}

因此,要调用所有这些代码,您可以执行以下操作:

IDisposable subscription1 = Subscribe<MyClass1>(MyMethod1);
IDisposable subscription2 = Subscribe<MyClass2>(MyMethod2);

Send(new MyClass1());
Send(new MyClass2());

subscription1.Dispose();

Send(new MyClass1());
Send(new MyClass2());

我得到的结果是:

MyMethod1
MyMethod2
MyMethod2

它显然是在订阅和取消订阅,而且它只是为传递的消息类型调用委托。我认为这涵盖了您正在尝试做的事情。