How can I dynamically create an Actionlt;Tgt; at runtime?(如何动态创建一个动作lt;Tgt;在运行时?)
问题描述
我希望能够在运行时执行以下等效操作:
I want to be able to do the equivalent to the following at runtime:
var action = new Action<ANYTHING AT RUNTIME>(obj => Console.WriteLine("Called = " + obj));
我知道我需要为 Action 获取正确的类型,但不确定如何使用 Delegate.Create 获取最终位.Type
表示 Action 定义中的 T.
I know I need to get the correct type for the Action, but not sure how to get the final bit using Delegate.Create. Type
represent T in the Action definition.
var actionType = typeof(Action<>).MakeGenericType(Type);
var constructor = actionType.GetConstructors()[0];
var @delegate = Delegate.CreateDelegate(actionType, <WHAT GOES HERE>);
人们似乎缺少的一点是我正在尝试创建一个 Action 实例,其中 T 不能静态指定,因为它是从派生自 Attribute 的类中使用的 - 这意味着 T 可以是任何东西,它不能被定义为泛型定义
the point people seem to be missing is I'm trying to create an instance of Action where T can not be specified statically because it is being used from a class derived from Attribute - this means T could be anything and it can not be defines as a generic definition
干杯
推荐答案
如果你知道你需要执行的操作是什么以及如何执行它而不考虑类型(如你的示例),为什么不只创建一个通用方法执行操作并以这种方式创建您的委托?
If you know what the operation you need to perform is and how to perform it regardless of type (as in your example) why not just make a generic method that performs the operation and create your delegate that way?
class Program
{
public static void Perform<T>(T value)
{
Console.WriteLine("Called = " + value);
}
public static Delegate CreateAction(Type type)
{
var methodInfo = typeof (Program).GetMethod("Perform").MakeGenericMethod(type);
var actionT = typeof (Action<>).MakeGenericType(type);
return Delegate.CreateDelegate(actionT, methodInfo);
}
static void Main(string[] args)
{
CreateAction(typeof (int)).DynamicInvoke(5);
Console.ReadLine();
}
}
这篇关于如何动态创建一个动作<T>在运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何动态创建一个动作<T>在运行时?


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01