匿名方法 Anonymouse Method

本文通过一个C#示例程序介绍了匿名方法的应用及对象初始化语法。代码展示了如何使用匿名方法为按钮点击事件和定时器事件添加处理逻辑,并演示了如何用对象初始化语法创建窗体和按钮。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/archive/2013/05/02/3054997.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值