深入理解CIL与动态程序集及C#动态类型
1. 理解ILGenerator方法
ILGenerator有一些重要方法,如下表所示:
| 方法 | 含义 |
| — | — |
| ThrowException() | 发出抛出异常的指令 |
| UsingNamespace() | 指定用于评估当前活动词法作用域中的局部变量和监视的命名空间 |
ILGenerator的关键方法是Emit(),它与System.Reflection.Emit.OpCodes类类型协同工作。OpCodes类通过只读字段公开了大量原始CIL操作码。
2. 发出动态程序集
为了说明在运行时定义.NET程序集的过程,我们来创建一个名为MyAssembly.dll的单文件动态程序集。该程序集中有一个HelloWorld类,其代码如下:
// This class will be created at runtime
// using System.Reflection.Emit.
public class HelloWorld
{
private string theMessage;
HelloWorld() {}
HelloWorld(string s) {theMessage = s;}
public string GetMsg() {return theMessage;}
public void SayHello()
{
System.Console.WriteLine("Hello from
超级会员免费看
订阅专栏 解锁全文
69

被折叠的 条评论
为什么被折叠?



