如何调用通用动作 ?

问题描述 投票:0回答:1

为了创建一个简单的事件总线来实现微服务的通信基础结构,我遇到了这个问题:

我如何调用具有不同通用类型的多个Action?

c# generics action
1个回答
0
投票

我对此问题的解决方案:

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"); }
}
© www.soinside.com 2019 - 2024. All rights reserved.