Convert Action to Action<object>

前端 未结 4 766
感动是毒
感动是毒 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:00

    Not sure what you mean by converting... Action is the generic declaration of an action delegate... if you want an action delegate that works on 'object' you would do something like:

    var myAction = new Action<object>(obj=> ... );
    
    0 讨论(0)
  • 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<string> within a new Action<object>. 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<Type, Action<object>>();
    Action<string> actionStr = s => Console.WriteLine(s);
    var actionObj = new Action<object>(obj => { var castObj = (V)Convert.ChangeType(obj, typeof(V)); actionStr(castObj); } );
    _actions.TryAdd(typeof(string), actionObj);
    
    0 讨论(0)
  • 2020-12-11 15:11

    I assume you have something like this:

    void Foo(Action<object> action) { }
    
    Action<something> myaction;
    

    And want to convert myaction so you can pass it to Foo.

    That doesn't work.

    Foo can pass any object to the action whose type derives from object. But myaction accepts only objects that derive from something.

    0 讨论(0)
  • 2020-12-11 15:26

    Here's a sample of what you ask for (type check can be added in last line to properly handle invalid cast exception to be more user-friendly):

    public Action<object> Convert<T>(Action<T> myActionT)
    {
        if (myActionT == null) return null;
        else return new Action<object>(o => myActionT((T)o));
    }
    

    May be you can give more details about the task though, because right now it looks a bit odd.

    0 讨论(0)
提交回复
热议问题