为了创建一个简单的事件总线来实现微服务的通信基础结构,我遇到了这个问题:
我如何调用具有不同通用类型的多个Action?
我对此问题的解决方案:
void Main()
{
var data = new object[] { new ProviderA(), new ProviderB() };
var events = new List<object> {
new Action<ProviderA>(provider => provider.Fire()),
new Action<ProviderB>(provider => provider.Fire())
};
Invoke(events[0], data);
Invoke(events[1], data);
}
void Invoke(object action, object[] data)
{
var genericActionType = action.GetType().GenericTypeArguments[0];
var dataObject = data.First(f => f.GetType() == genericActionType);
var genericAction = typeof(Action<>).MakeGenericType(dataObject.GetType());
genericAction.GetMethod("Invoke").Invoke(action, new object[]{ dataObject });
}
public class ProviderA
{
public void Fire() { Console.WriteLine("Provider A fired"); }
}
public class ProviderB
{
public void Fire() { Console.WriteLine("Provider B fired"); }
}