在运行时动态创建函数 [英] Creating a function dynamically at run-time

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

问题描述

这可能甚至不可能,但是我也会问。
是否可以创建一个接收字符串的函数,然后将其用作lambda中使用的运算符(=>)的右侧参数。



实际上,我想做的是在运行时能够重新定义特定类的特定方法。我想在程序运行时写下一个函数,并将其附加到代理。

解决方案

最简单的方法可能是DLINQ,因为TcKs建议。



最快(我相信3.5中)是创建一个 DynamicMethod 。它也是最可怕的方法。您本质上是使用IL来构建一种方法,它与机器语言编写代码的感觉大致相同。



我需要这样做来动态地附加一些事件处理程序事情或另一个(嗯,我不需要这样做,我只是想使单元测试事件更容易)。当时看起来有点令人生畏,因为我不了解IL,但我想出了一个简单的方式来实现这一点。



你所做的是创建一个完全符合你想要的方法。越紧凑越好。我会提供一个例子,如果我能弄清楚你正在做什么。您在DLL项目中的类中编写此方法,并在发布模式下进行编译。然后打开反光板中的DLL并反汇编您的方法。反射器可以让您选择要拆分的语言 - 选择IL。您现在有了您需要添加到动态方法的确切调用。只需按照MSDN上的示例,将示例的IL切换为您所反映的方法的代码。动态方法(一旦构造)以与编译方法大致相同的速度调用(看到一个测试,其中可以在〜20ms内调用动态方法,反射占用了200ms)。


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?

解决方案

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

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.

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.

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.

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天全站免登陆