如何动态创建Action< T>在运行时?

编程入门 行业动态 更新时间:2024-10-10 08:22:19
本文介绍了如何动态创建Action< T>在运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在运行时能够等同于以下内容:

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。 在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可以没有静态指定,因为它是从属性派生的类中使用的 - 这意味着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

干杯

Cheers

推荐答案

如果你知道你需要执行的操作是什么,如何执行它,不管类型如何,只需做一个通用的方法来执行操作并创建你的代理方式?

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(); } }

更多推荐

如何动态创建Action&lt; T&gt;在运行时?

本文发布于:2023-11-09 08:05:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571822.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   Action   amp   lt   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!