Convert Action to Action<object>

前端 未结 4 868
感动是毒
感动是毒 2020-12-11 14:19

I am stuck.

How do I convert the Action to an Action in C#?

Regards Magnus

4条回答
  •  我在风中等你
    2020-12-11 15:01

    I was looking for a way to do this today and stumbled upon this post. Really, the only simple way I found to do it was to wrap Action within a new Action. In my case, I was pushing my Actions into a Concurrent Dictionary, and then retrieving them by type. Effectively, I was processing a queue of messages where actions could be defined to handle messages with a particular typed input.

    var _actions = new ConcurrentDictionary>();
    Action actionStr = s => Console.WriteLine(s);
    var actionObj = new Action(obj => { var castObj = (V)Convert.ChangeType(obj, typeof(V)); actionStr(castObj); } );
    _actions.TryAdd(typeof(string), actionObj);
    
        

    提交回复
    热议问题