简体   繁体   English

使用Activator.CreateInstance创建功能 <T> 实例

[英]Using Activator.CreateInstance to create Func<T> instances

Does anybody know how to dynamically create a Func<T> instance? 有人知道如何动态创建Func<T>实例吗?

//Create the Func type

Type funcType = typeof(Func<>).MakeGenericType(typeof(string)); 

//How do I pass a reference to the anonymous method? 

Activator.CreateInstance(funcType, () => "test");

This does not compile: 这不会编译:

Cannot convert lambda expression to type object[] because it is not a delegate type 无法将Lambda表达式转换为object[]类型,因为它不是委托类型

Anyone? 任何人?

You need to use Expression trees: 您需要使用表达式树:

var func = Expression.Lambda(Expression.Constant("test")).Compile();
var result = func.DynamicInvoke();

I don't think you can. 我认为你不能。 This blog goes some way to explaining the issue. 该博客以某种方式解释了该问题。 I suggest you look for an alternative approach. 我建议您寻找一种替代方法。 Can you use expression trees instead? 您可以改用表达式树吗?

You need a object which can be converted into System.Object , for this you need to create a delegate like Func<String> first. 您需要一个可以转换为System.Object的对象,为此,您需要首先创建一个类似于Func<String>的委托。 So it makes no sence for me to create the Func<T> at runtime. 因此,在运行时创建Func<T>对我来说毫无意义。

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

相关问题 Activator.CreateInstance - 如何创建具有参数化构造函数的类的实例 - Activator.CreateInstance - How to create instances of classes that have parameterized constructors 使用Activator.CreateInstance时解析注入的实例 - Resolving injected instances when using Activator.CreateInstance 在运行时加载程序集并使用Activator.CreateInstance()创建实例 - Loading assemblies at runtime and creating instances using Activator.CreateInstance() Activator.CreateInstance(string)和Activator.CreateInstance <T> () 区别 - Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference 结合使用Activator.CreateInstance()和属性 - Using Activator.CreateInstance() with properties 使用Activator.CreateInstance创建类的实例并将Interface注入构造函数 - Using Activator.CreateInstance to create instance of a class and inject Interface to constructor 无法使用Activator.CreateInstance创建COM类的实例 - Unable to Create the instance of COM class using Activator.CreateInstance RabbitMq EasyNetQ使用Activator.CreateInstance创建消息 - RabbitMq EasyNetQ Create message using Activator.CreateInstance 是否可以使用Activator.CreateInstance()使用参数构造函数创建泛型工厂? - Is it possible to create a generic factory with constructor with parameters using Activator.CreateInstance()? 默认(T)与Activator.CreateInstance(T) - default(T) versus Activator.CreateInstance(T)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM