匿名方法 Anonymouse Method

DEMO: Object Initializer, Anonymouse Method.

using System;
using System.Windows.Forms;

public class MyClass
{
    public static void Main()
    {
        Button btnHello = new Button();
        btnHello.Text = "&Hello";
        btnHello.Click += delegate{//Anonymouse Method
            MessageBox.Show("Yes! It's the Anonymouse Method!");
        };
        
        Form form = new Form{Height=255, Width=255//Object Initializer
            MaximizeBox=false, FormBorderStyle = FormBorderStyle.FixedSingle};
        form.MouseMove += delegate(object Sender, MouseEventArgs e)
        {//delegate{        //Anonymouse Method with Parameters
            form.BackColor = System.Drawing.Color.FromArgb(e.X<0?0:e.X,e.Y<0?0:e.Y,255);
        };
        
        Timer tmr = new Timer{ Enabled = true, Interval = 1000};
        tmr.Tick += delegate{
            form.Text = DateTime.Now.TimeOfDay.ToString();
        };
        
        form.Controls.Add(btnHello);
        Application.Run(form);
    }
}

 上面代码经过Reflector反编译以后,稍加修改也能运行! 看看操蛋的操作符吧 =>

using System;
using System.Drawing;
using System.Windows.Forms;

public class MyClass
{
    public static void Main()
    {
        Button button = new Button {
            Text = "&Hello"
        };
        button.Click += (param0, param1) => MessageBox.Show("Yes! It's the Anonymouse Method!");
        Form form = new Form {
            Height = 0xff,
            Width = 0xff,
            MaximizeBox = false
        };
        form.MouseMove += (Sender, e) => {form.BackColor = Color.FromArgb(e.X, e.Y, 0xff);};
        Timer timer = new Timer {
            Enabled = true,
            Interval = 0x3e8
        };
        timer.Tick += (param0, param1) => {form.Text = DateTime.Now.TimeOfDay.ToString();};
        form.Controls.Add(button);
        Application.Run(form);
    }
}

再来看看ILDASM反编译的结果:注意类的嵌套,再有就是方法名称<Main>b_4类似的命名是错误的。

原文地址:https://www.cnblogs.com/flaaash/p/3054997.html