gpt4 book ai didi

C#根据参数类型订阅事件?

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:29 25 4
gpt4 key购买 nike

我有一个 Commander处理命令的类。所有这些命令都实现了 ICommand界面。基本上是命令模式...

现在我想创建类似于 event 的东西对于每种特定类型的命令,实际上没有为指挥官中的每种特定类型创建事件。指挥官不应耦合到每种类型的命令。

所以我的命令有一个方法void Subscribe<T>(Action<T> callback) where T: ICommand .如果订阅者使用 void MyAttackCommandHandler(AttackCommand att) 方法调用它作为参数,我希望订户仅获得 AttackCommands 的回调.然而,另一个类也可以订阅不同的命令。

我尝试创建一个字典,将参数类型(命令类型)映射到订阅者列表:Dictionary<Type, List<Action<ICommand>>> _subscriptions ,然后我的订阅方法将类似于:

public void Subscribe<T>(Action<T> callback)
where T: ICommand
{
Type type = typeof(T);
if (_subscriptions.ContainsKey(type))
{
List<Action<ICommand>> subscribtions = _subscriptions[type];
subscribtions.Add(callback);
}
else ... //create a new entry in _subscriptions
}

但这不起作用,因为 callback不是 Action<ICommand> 类型, 但属于 Action<AttackCommand>例如。

如何干净地实现这一点?

谢谢!

最佳答案

试试这个

subscribtions.Add(i => callback((T)i));

如果上述方法不起作用,请提供一个完整的示例来说明您的问题。像这样:

using System;
using System.Collections.Generic;

namespace Example
{
class Program
{
static void Main(string[] args)
{
Commander C = new Commander();
C.Subscribe((MyCommand i) => { Console.WriteLine(i.Value); });
C.Subscribe((SquareMyCommand i) => { Console.WriteLine(i.Value); });
C.Subscribe((SquareMyCommand i) => { Console.WriteLine("**" + i.Value + "**"); });

C.Do(new MyCommand(2));//1 callback , Prints 2
C.Do(new SquareMyCommand(3));//2 callbacks, Prints 9 , **9**
Console.ReadLine();
}
}

public class Commander
{
Dictionary<Type, List<Action<ICommand>>> dictionary = new Dictionary<Type, List<Action<ICommand>>>();
public void Subscribe<T>(Action<T> callback) where T : ICommand
{
Type type = typeof(T);

List<Action<ICommand>> subscribtions = null;
dictionary.TryGetValue(type, out subscribtions);
if (subscribtions == null)
{
subscribtions = new List<Action<ICommand>>();
dictionary.Add(type, subscribtions);
}
subscribtions.Add(i => callback((T)i));
}

public void Do<T>(T t) where T : ICommand
{
foreach (var item in dictionary[t.GetType()])
item(t);
}
}

public class MyCommand : ICommand
{
public MyCommand(int x) { Value = x; }
public int Value { get; set; }
}
public class SquareMyCommand : ICommand
{
public SquareMyCommand(int x) { Value = x * x; }
public int Value { get; set; }
}
public interface ICommand
{
int Value { get; set; }
}
}

关于C#根据参数类型订阅事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34581701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com