C#反射,改变方法体 [英] C# Reflection, changing a method's body

查看:365
本文介绍了C#反射,改变方法体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
是否有可能在运行时改变方法的主体?


Is it possible to change the body of method during runtime?

class Person
{
    public void DoSth()
    { Console.WriteLine("Hello!"); }
}



我想有一个简单的输入字段(如文本框),我。可以在运行时编写方法体的源代码

I wanted to have a simple input field (like a textbox) where I can write the method body source code during runtime.

文本框可以包含类似的数据:

The textbox may contain data like:

for (int i = 0; i < 5; i++)
     Console.WriteLine(i);



这应该excecuted时

which should be excecuted when

new Person().DoSth()

被调用。

时(或如何),这是可能在C#(使用反射)?结果
感谢您的帮助提前。

Is (or how is) this possible in C# (using Reflection)?
Thanks for your help in advance.

编辑:?结果
如果以上是不可能的,是有可能在运行时创建一个新的方法,并调用它


If the above isn't possible, is it possible to create a new method during runtime and call it?

推荐答案

Reflection.Emit的是在运行时...
http://msdn.microsoft.com/en-us/library/8ffc3x75(v = VS.90)的.aspx

Reflection.Emit is one way of generating IL at runtime... http://msdn.microsoft.com/en-us/library/8ffc3x75(v=VS.90).aspx

轻型代码生成是另一种...
http://blogs.msdn.com/b/joelpob/archive/2004/03/31/105282.aspx

Lightweight code generation is another... http://blogs.msdn.com/b/joelpob/archive/2004/03/31/105282.aspx

然而,无论是拿C#和编译。为此,将最有可能需要调用C#编译器。

However, neither take C# and compile it. For this you'll most likely need to invoked the C# compiler.

什么是您的使用情况(你为什么想这样做)?没有与您的应用程序域中运行的代码安全性的考虑,所以你需要找出你会如何处理这个问题。

What is your use case (why do you want to do this)? There are security considerations with running code within your app domain, so you need to work out how you'd deal with this.

这篇关于C#反射,改变方法体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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