Emit Learning-Basic articles-helloworld

Source: Internet
Author: User
Tags emit

In accordance with the industry's practice, we use one of the simplest examples-"Hello world"-to begin our emit journey. The relevant code and comments for the example are as follows:

 using System;

Using System.Collections.Generic;

Using System.Text;


Using System.Reflection.Emit;

        Namespace Emitexamples.helloworld {class Program {///<summary>///a delegate to invoke a dynamic method


        </summary> Private delegate void Helloworlddelegate (); static void Main (string[] args) {//define a dynamic method named HelloWorld, no return value, no parameter DynamicMethod hell


            Oworldmethod = new DynamicMethod ("HelloWorld", NULL, NULL);

            Create an MSIL generator to generate code for the dynamic method ILGenerator Helloworldil = Helloworldmethod.getilgenerator ();

            The Hello world! word that will be output is Fuganga loaded onto the stack helloworldil.emit (opcodes.ldstr, "Hello world!");

            Call Console.WriteLine (string) method output Hello world! Helloworldil.emit (Opcodes.call, typeof (Console).

            GetMethod ("WriteLine", new type[] {typeof (String)}));

            Method ends, returns Helloworldil.emit (Opcodes.ret); Completes the creation of the dynamic method, and gets the one that can execute the dynamic sideThe commission of the law helloworlddelegate HelloWorld = (helloworlddelegate) helloworldmethod.createdelegate (typeof (Helloworlddel

            egate));

            Executes the dynamic method that will print the Hello world! on the screen

        HelloWorld (); }} 

Here we just use this example to give you an intuitive understanding of emit and IL, and the methods used will be specifically explained in later chapters

This article supporting source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.