Reputation: 71111
How can accomplish the following in C#?
var someType = new CustomerMessageHandler<CustomerMessage>();
var nType = someType.GetGenericArguments().First().GetType();
// except the next line of code would be a (Action<nType>)
var a = new Action<string>();
Does Reflection.Emit, Expressions, or F# have a good solution for this?
Note: A 'convention-based' approach is not an option for me. And I'm asking to see if this is even possible to push my C#/F# skills.
Upvotes: 2
Views: 180
Reputation: 34832
Sure, MakeGenericType
will be able to do this for you.
Type genericAction = typeof(Action<>);
var someType = new CustomerMessageHandler<CustomerMessage>();
var nType = someType.GetGenericArguments().First().GetType();
var actionType = genericAction.MakeGenericType(new[] { nType });
Note however that an Action<T>
is a delegate that should actually DO something... So you'd need to write a body for that:
var actualMethod = Delegate.CreateDelegate(actionType, **your method info here**);
Upvotes: 5