`

c# - reflection in the System.Reflection.Emit namespace - ModuleBuilder

    博客分类:
  • C#
c# 
阅读更多

The namespace of System.Reflection.Emit is the rennovated namespace for reflection based APIs. In this topic, we are going to discuss the how to use the ModuleBuilder from this particular namespace. 

 

 

the original MSDN documentation on the ModuleBuilder is avaiable here in this page: Module Builder Class 

 

 

public class CodeGenerator
  {
    AssemblyBuilder myAssemblyBuilder;

    public CodeGenerator()
    {
      // Get the current application domain for the current thread
      AppDomain myCurrentDomain = AppDomain.CurrentDomain;

      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "TempAssembly";              // looks like we are creating the assemblies on the fly

      // Define a dynamic assembly in the current application domain.
      myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run); // indicate what kind of acces the generated assemblies is supposed to used!

      // now we have the Assembly, we can then create the module in this assembly
      ModuleBuilder myModuleBuilder = myAssemblyBuilder.DefineDynamicModule("TempModule");

      // Define a runtime class with specified name and attributes 
      TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("TempClass", TypeAttributes.Public);

      // Add a Field, which is called "Greeting" to the class, with the specified attribute and type.
      FieldBuilder greetingField = myTypeBuilder.DefineField("Greeting", typeof(string), FieldAttributes.Public);

      Type[] myMethodArgs = { typeof(string) }; // type of the Method Args is defined as such

      // Add 'MyMethod' method to the class, with teh specified attributes and signature 
      MethodBuilder myMethod = myTypeBuilder.DefineMethod("MyMethod", MethodAttributes.Public, CallingConventions.Standard, null, myMethodArgs);

      ILGenerator methodIL = myMethod.GetILGenerator();
      methodIL.EmitWriteLine("In the method...");
      // the following code has the same effect as 
      //  anonymous_fun(string arg) { 
      //    GreetingField =  arg;
      //    return;
      //  }
      methodIL.Emit(OpCodes.Ldarg_0);                 // load this pointer
      methodIL.Emit(OpCodes.Ldarg_1);                 // load the first argument, which "value"
      methodIL.Emit(OpCodes.Stfld, greetingField);    // store the value of "value" to the GreetingField
      methodIL.Emit(OpCodes.Ret);                     // return from the call
      myTypeBuilder.CreateType();                     // Generate the code


    }
    public AssemblyBuilder MyAssembly
    {
      get
      {
        return this.myAssemblyBuilder;
      }
    }
  }

  public class TestClass
  {
    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public static void Main()
    {
      CodeGenerator myCodeGenerator = new CodeGenerator();

      // Get the Assembly builder for 'myCodeGenerator' object.
      AssemblyBuilder myAssemblyBuilder = myCodeGenerator.MyAssembly;
      // Get the module builder for the above assembly builder object.
      ModuleBuilder myModuleBuidler = myAssemblyBuilder.GetDynamicModule("TempModule");

      // Display the fully qualified name of the moduel
      Console.WriteLine("The fully qualified name and path to this " + "module is :" + myModuleBuidler.FullyQualifiedName);

      // 
      Type myType = myModuleBuidler.GetType("TempClass");
      MethodInfo myMethodInfo = myType.GetMethod("MyMethod");

      // Get the token used to identify the method iwthin this module
      // SO be careful that the method does not return the MethodInfo, but rather return 
      // the method tokens
      MethodToken myMethodToken = myModuleBuidler.GetMethodToken(myMethodInfo);

      Console.WriteLine("Token used to identify the method of 'myType'" + "within the module is {0:x}", myMethodToken.Token);
      object[] args = { "Hello." };
      object myObject = Activator.CreateInstance(myType, null, null);
      myMethodInfo.Invoke(myObject, args);
    }
  }
 

 

As you can see:

 

 

  • there are different types of builder, e.g. ModuleBuilder, TypeBuilder,  FieldBuidler, MethodBuilder which build Module, Type,  Field or Method;
  • The various xxxBuilder class has the DefineXXX method to get a builder of subordinate constructs, e.g. ModuleBuilder.DefienType return TypeBuilder.
  • Each Builder is a subclass to XXXInfo, e.g. FiledBuilder is subclass to FieldInfo.
  • To generate the IL code, you may use the ILGenerator, and there is a bunch of Emit calls to generate the body of the method.
  • From each builder, you can query some adjunct construct, e.g. you can get ModuleBuilder from AssemblyBuilder...

 

 

分享到:
评论

相关推荐

    最新nodejs安装包 v8.12.0-linux-x64.tar.xz

    eventEmitter.emit('data_received'); } // 绑定 connection 事件处理程序 eventEmitter.on('connection', connectHandler); // 触发 connection 事件 eventEmitter.emit('connection'); console.log("程序...

    Managed.Reflection, System.Reflection [.Emit ]的托管替换.zip

    Managed.Reflection, System.Reflection [.Emit ]的托管替换 Managed.ReflectionManaged.Reflection 是对 System.Reflection 和 System.Reflection.Emit的完全管理的替换。 System.Reflection 不同,它不绑定到

    iperf-3.9-win64.zip

    --timestamps <format> emit a timestamp at the start of each output line (using optional format string as per strftime(3)) -d, --debug emit debugging output -v, --version show version information ...

    PyPI 官网下载 | fluent_logger-0.10.0-py2.py3-none-any.whl

    4. 记录日志:调用logger的`emit`方法,传递日志数据,例如`logger.emit('logtag', {'key': 'value'})`。 fluent_logger库的一大特点是支持结构化的日志数据,这使得日志数据更加易读和分析。此外,它还提供了异步...

    Vue.js-2.0-参考手册.CHM

    包括组件定义、props传递、事件通信($emit和$v-on)、自定义指令、插槽等内容。 3. **状态管理**:Vue 2.0引入了Vuex作为官方推荐的状态管理工具,用于集中管理组件间的共享状态。学习Vuex的基本原理、状态、动作、...

    微信小程序socket.io客户端, 支持微信小程序、支付宝小程序socket.io-mp-client-master.zip

    - 发送数据:`socket.emit('event-name', data);` - 监听数据:`socket.on('event-name', (res) => { console.log(res); });` 6. **错误处理**:库通常会提供错误处理机制,如连接失败、断线重连等,开发者需要...

    PyPI 官网下载 | python_socketio-3.0.1-py2.py3-none-any.whl

    4. **Namespace**:命名空间是SocketIO的一个特性,允许在一个SocketIO服务器上创建多个独立的通信通道。每个命名空间可以有不同的事件和逻辑,这样可以在同一个Socket连接上处理不同的数据类型或应用场景。 5. **...

    swift-socket.io-client-swiftSocket.IO客户端

    6. **API接口**:Swift Socket.IO客户端提供了丰富的API,如`emit()`用于发送事件,`on()`用于监听事件,以及`disconnect()`用于断开连接等,方便开发者集成到自己的应用中。 7. **错误处理**:客户端还提供了错误...

    PyPI 官网下载 | socketIO-client-2-0.7.4.tar.gz

    socketIO.emit('my_request', {'message': 'Hello Server!'}) ``` 在分布式和云原生环境(Cloud Native)中,socketIO-client因其实时性和可扩展性得到了广泛应用。例如,在Zookeeper这样的分布式协调服务中,...

    HiChat-master--计网设计.zip

    当用户输入消息并发送时,触发`emit`方法将消息发送到服务器。 - **展示聊天记录**:服务器广播的消息会在客户端接收到,更新聊天界面显示最新的聊天记录。 5. **HiChat-master项目分析** "HiChat-master--计网...

    使用MSIL采用Emit方式实现C#的代码生成与注入.rar

    MSIL使得开发者能够在运行时动态生成和执行代码,这是通过System.Reflection.Emit命名空间中的类来实现的。本教程将深入探讨如何使用MSIL和Emit API来生成和注入C#代码。 首先,让我们了解Emit API的基本概念。Emit...

    Interop Without PInvoke - Consuming Native Libraries in C#.-DynamicLib

    相反,C#的`System.Reflection.Emit`命名空间提供了动态生成IL代码的能力,这使得在运行时创建类型和方法成为可能。通过这种方式,我们可以动态地构建一个代理类,该类在内部调用本地库的函数,从而避免了P/Invoke的...

    AngularJS - Novice to Ninja.pdf.pdf )

    The Watchers in AngularJS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 The $watchCollection() Function . . . . . . . . . . . . . . . . . . . . . . . 56 The $apply() Function ...

    Vue2.x和Vue3.x面试常问知识点-面试题-JackieDYH - CSDN博客.pdf

    - Vue2.x中,组件间通信可以通过props、事件($emit/$on)、Vuex状态管理或非父子组件间的Bus(事件总线)。 - Vue3.x增加了提供通信的新方法,如提供和注入(provide/inject)以及使用Context API。 面试中,...

    Emit学习之旅

    Emit学习之旅是一个深入探索C# Emit技术的教程,它为开发者提供了动态生成IL(Intermediate Language)代码的能力。Emit是.NET Framework的一部分,允许程序员在运行时构建和执行方法,这是实现元编程的重要工具。...

    高考英语作文万能模板附范文.doc

    - 解决方案一:One possible solution is ①-----------------------. Although it has the advantage of ②-----------------, there might be a potential drawback ③-----------------. - 解决方案二:Another ...

    learn-qt-qchart-plot-newdisplay.zip

    using namespace QtCharts; private: //曲线 QSplineSeries* line; //绘图变量和坐标 QChart* chart; //发来数据的接收槽函数 private slots: void receive_list(QVector<QPointF> list); 在子.cpp中 line =...

    socketIO使用教程--含代码demo.zip

    io.emit('message', data); }); }); ``` 3. **客户端集成**:在 HTML 页面中,引入 `socket.io-client` 库,并创建一个 `Socket` 实例,连接到服务器。然后,可以监听服务器发送的事件,以及发送自定义事件。 ...

    PyPI 官网下载 | fluent-logger-0.6.0.tar.gz

    然后,他们可以调用对象的方法来记录不同级别的日志事件,例如`emit()`方法,同时传递事件的标签和数据。 在分布式和云原生环境中,这种日志记录方案的优势在于它能够集中管理大量节点的日志,方便监控、搜索和分析...

    Node.js-node和socket.iol实现简易聊天室

    console.log(`Message "${msg}" stored in DB.`); } catch (error) { console.error(error); } io.emit('chat message', msg); }); ``` 这里我们创建了一个名为`messages`的表,用于存储聊天记录。当收到新...

Global site tag (gtag.js) - Google Analytics