BuddyJoe
BuddyJoe

Reputation: 71111

How to create an Action<T> with Reflection where T is a discovered generic Type

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

Answers (1)

Haney
Haney

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

Related Questions