【问题标题】:Can I subscribe to a generic Action with a concrete method?我可以使用具体方法订阅通用 Action 吗?
【发布时间】:2023-03-19 11:18:01
【问题描述】:

See Enigmativity's answer for a much clearer phrasing of this question.


我有一个我正在注册的通用 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

【问题讨论】:

  • “我是否可以使用具有具体类型的方法订阅通用动作?” -- 你试过了吗? 发生了什么?您具体在哪些方面需要帮助?
  • @PeterDuniho 是的,我已经尝试了我能想到的一切。我不知道怎么做。如果您觉得我的研究不够充分,请告诉我您还想看什么。
  • 顺便说一句,您在这里使用公共非readonly 变量是错误的代码。您应该使用正确的 C# event 声明。它的工作原理相同,但会确保只有实现类才能访问委托字段。
  • @PeterDuniho 顶部的代码只是为了解释这个问题。底部的代码是我目前在项目中实际拥有的代码。
  • 简短版本是“否”,因为它不安全。如果你可以分配例如将 MyClass 参数作为参数的方法传递给委托类型 Action&lt;IMyInterface&gt;,那么任何对该委托类型的引用都可以将 any IMyInterface 引用传递给您的方法,即使它不是 @ 987654333@ 你的方法需要。副本为完全通用的解决方法可以工作的一种情况提供了建议,但请注意,它通过从根本上将代码设计更改为类型安全的。

标签: c# generics publish-subscribe


【解决方案1】:

您问题中的类型似乎有点乱码 - 问题顶部的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 方法,因为这将迫使您保持对原始委托的引用以删除委托。使用一个返回 IDisposableSubscribe 方法更容易让您取消订阅。与许多不同类型的代表相比,持有一堆一次性用品要容易得多 - 否则这是一种“从煎锅到火中”的事情。

这就是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&lt;Delegate&gt;,因为它可以存储任何委托类型。

这是您需要的 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();
        }
    }
}

现在是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

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

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 2018-09-26
    • 2017-11-23
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    相关资源
    最近更新 更多