在运行时动态地创建功能 [英] Creating a function dynamically at run-time

查看:126
本文介绍了在运行时动态地创建功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能甚至是不可能做到这一点,但我会问反正。 是否有可能创建一个接收一个字符串,然后使用它作为拉姆达使用右侧参数的去操作符(=>)函数?

It probably isn't even possible to do this, but I will ask anyway. Is it possible to create a function that receives a string and then uses it as a right side argument for the goes to operator (=>) used in lambda?

其实,我想要做的就是能够在运行时重新定义一个特定类的具体方法。我想记下该程序运行并将其连接到一个委托功能。这可能吗?

Actually, what I want to do is to be able to redefine an specific method of a specific class during runtime. I want to be write down a function with the program running and attaching it to a delegate. Is it possible?

推荐答案

要做到这一点是可能DL​​INQ作为第三文化孩子提出的最简单的方法。

The easiest way to do it is probably DLINQ as TcKs suggested.

最快的(我相信,在3.5)是创建一个<一个href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx">DynamicMethod.它也是最可怕的方式为好。你基本上建立使用IL的方法,其中有大约相同的感觉写作code机器语言。

The fastest (I believe, in 3.5) is to create a DynamicMethod. Its also the scariest method as well. You're essentially building a method using IL, which has about the same feel as writing code in machine language.

我需要做动态附加事件处理程序在某些事情或其他(好,我也没必要这么做,我只是想单元测试的事件更容易)。这似乎有点令人生畏的时候,因为我不知道垃圾约IL,但我想通了,要做到这一点的简单方法。

I needed to do this to dynamically attach event handlers in some thing or another (well, I didn't need to do it, I just wanted to make unit testing events easier). It seemed a bit daunting at the time because I don't know crap about IL, but I figured out a simple way to accomplish this.

你要做的就是,做你想要什么创建一个方法。越紧越好。我提供了一个例子,如果我能找出你想要做的事情。你写这个方法在一个类中的DLL项目中,并在释放模式编译。然后,你打开反射器的DLL和拆卸的方法。反射给你,你要拆开来用什么语言的选项 - 选择IL。现在,你有你需要添加到您的动态方法的具体要求。只要按照MSDN上的例子,从切换的例子的IL您反映的方法'code。

What you do is create a method that does exactly what you want. The more compact the better. I'd provide an example if I could figure out exactly what you're trying to do. You write this method in a class within a DLL project and compile it in release mode. Then you open the DLL in Reflector and disassemble your method. Reflector gives you the option of what language you wish to disassemble to--select IL. You now have the exact calls you need to add to your dynamic method. Just follow the example on MSDN, switching out the example's IL for your reflected methods' code.

动态方法,一旦建成,调用在大约相同的速度编译的方法(看到一个测试,动态方法可称为〜20ms的,其中反映了200ms以上)。

Dynamic methods, once constructed, invoke at about the same speed as compiled methods (saw a test where dynamic methods could be called in ~20ms where reflection took over 200ms).

这篇关于在运行时动态地创建功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆