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.

有帮助吗?

解决方案

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**);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top