任何简单的方法来创建方法和C#动态设置它的身上? [英] Is any simple way to create method and set its body dynamically in C#?

查看:174
本文介绍了任何简单的方法来创建方法和C#动态设置它的身上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我抱法体字符串。我要动态地创建方法。但我不知道如何设置它的身体。我看到了使用的CodeDOM非常繁琐的方式。我看到了使用发射具有操作码。任何方式使用现成代码字符串变量?



 字符串method_body =返回\你好,世界!\ ;; //有方法体
DynamicMethod的DM =新System.Reflection.Emit.DynamicMethod(My_method,
typeof运算(字符串),新类型[] {}); //任何方法来创建动态的方法
//任何方式来设置体
字符串结果=(字符串)dm.Invoke(...); //我需要写导致变量


解决方案

您需要一起来看看这些命名空间:

 的System.Reflection; 
System.CodeDom.Compiler;
Microsoft.CSharp;

这可以让你开始:的 http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm


I hold body of method in string. I want to create method dynamically. But I don't know, how to set its body. I saw very tedious way using CodeDom. And I saw using Emit with OpCodes. Is any way to use ready code from string variable?

string method_body = "return \"Hello, world!\";"; //there is method body
DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("My_method",
                 typeof(string), new Type[] { }); //any way to create method dynamically
//any way to set body
string result = (string)dm.Invoke(...); //I need write result in variable

解决方案

You need to take a look at these namespaces:

System.Reflection;
System.CodeDom.Compiler;
Microsoft.CSharp;

This may get you started: http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm

这篇关于任何简单的方法来创建方法和C#动态设置它的身上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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