Convert Action<T> to Action<object>
How do I convert Action<T>
to Action<Object>
in开发者_如何学Python C#?
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.
You can add generic parameter like this
Action<object> Function<T>(Action<T> act) where T : class
{
return (Action<object>)act;
}
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.
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=> ... );
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);
精彩评论