繁体   English   中英

如何创建动作 <T> 与反射,其中T是发现的泛型类型

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

如何在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>();

Reflection.Emit,Expression或F#是否对此有一个好的解决方案?

注意:我无法选择“基于约定”的方法。 我想看看是否有可能提高我的C#/ F#技能。

当然, MakeGenericType将能够为您执行此操作。

Type genericAction = typeof(Action<>);
var someType = new CustomerMessageHandler<CustomerMessage>();
var nType = someType.GetGenericArguments().First().GetType();
var actionType = genericAction.MakeGenericType(new[] { nType });

但是请注意, Action<T>是实际上应该执行某些Action<T>的委托...因此,您需要为此编写一个主体:

var actualMethod = Delegate.CreateDelegate(actionType, **your method info here**);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM