我可以通过具体方法订阅通用操作吗? [英] Can I subscribe to a generic Action with a concrete method?

查看:50
本文介绍了我可以通过具体方法订阅通用操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关此问题的更清晰措辞,请参见谜题的答案.

我要注册一个通用的 Action ,然后将其转换为期望的类型:

I have a generic Action that I am registering for, and then casting to the type I am expecting:

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 可以像这样:

But I want to be able to subscribe with a method that already dictates the type so I can avoid the extra step of casting. Is it possible to only subscribe to MyActions such that IMyInterface has a specific type? So that MyMethod can be like this:

public void MyMethod(MyClass myClass)
{

}

之所以尝试执行此操作,是因为我正在编写使用特定类型的消息传递系统.我正在使用泛型来确定要订阅的消息.我认为这部分内容不会影响我的问题,但这是下面的样子:

The reason I am trying to do this is because I am writing a messaging system which uses the specific type. I am using generics to determine which messages to subscribe to. I don't think this part affects my question, but here is what that looks like:

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 吗?

So is it possible for me to subscribe to a generic Action with a method that has a concrete type?

推荐答案

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

The types in your question seemed to be a bit garbled - IMyInterface at the top of the question and IMessage in the bottom part. I've assumed these interfaces and basic methods:

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");
}

现在,我进一步简化了您的代码,使其没有 SubscribeMessage UnsubscribeMessage 方法,因为这将迫使您维护对要删除的原始委托的引用一位代表.具有单个 Subscribe 方法返回一个允许您退订的 IDisposable 方法更容易.与许多不同类型的代表相比,拿着一堆一次性用品要容易得多-否则这是从平底锅里掉进火里".那样的东西.

Now, I've further simplified your code to not have a SubscribeMessage and an UnsubscribeMessage method as this will force you to maintain a reference to the original delegate to remove a delegate. It's easier to have a single Subscribe method that returns an IDisposable that lets you unsubscribe. It's much easier to hold a bunch of disposables than many different types of delegates - otherwise it's an "out of the frying pan and into the fire" kind of thing.

这是订阅所需的全部内容:

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));
}

我已不再需要检查重复项.那应该是调用代码的责任.在某些情况下,两次调用代表可能是有效的.将其留给调用代码,以确保这是一件明智的事情.

I've removed the need to check for duplicates. That should be a responsibility of the calling code. There are situations where calling a delegate twice might be valid. Leave it to the calling code to make sure it's a sane thing to do or not.

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

I've also used a List<Delegate> as that enables any delegate type to be stored.

这是您需要的 ActionDisposable 类:

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();
        }
    }
}

现在是发送:

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);
        }
    }
}

因此,您可以调用所有这些代码:

So to call all of this code you can do:

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

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

It clearly is subscribing and unsubscribing, and it's only calling the delegates for the type of message passed. I think that covers off on what you're trying to do.

这篇关于我可以通过具体方法订阅通用操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆