ITeye博客

委托和事件

ooaer · 2010-06-10 16:24 · C# · 编程语言 · Markdown

1.委托


using System;
using System.Windows.Forms;
public class WinForm
{
 // public static void Main()
 // {
  // Form win = new Form();
  // Button btn = new Button();
  // btn.Text="ClickMe";
  // win.Controls.Add(btn);
  // Application.Run(win);//后台窗口实现
 // }
}
public class WinTwo : Form
{
 private Button btn;
 public WinTwo()
 {
   btn = new Button();
   btn.Text = "fuck";
   this.Controls.Add(btn);//在窗口中增加一个按钮
 }
//////////////////////////////////////////////////////////////////////////////////////////////////////
 public static void Main()
 {
   MyDelegate dgt2;
   Test tst = new Test();
   tst.tt();
   public event EventHandler evt;//事件声明
   evt = new dgt2(A.f);
      WinTwo win2 = new WinTwo();
   Application.Run(win2);
   
 }
}

public Delegate void MyDelegate(int a);//委托申明,其中MyDelegate 是一个类。
public class Test  //用委托处理事件
{
 public MyDelegate dgt  = new MyDelegate(A.f);//用委托申明对象并且实例化,参数为要制定的方法
 public void tt()
 {
    dgt(3); //通过委托来调用方法,其中3为委托方法的参数
 }
}
public class A
{
 public void f(int a)//委托方法
 {
  int b  = a;
 }
}

2.事件 要想成功触发事件执行某些方法,必须先声明一个委托,然后,用这个委托去申明事件,事件加载想要的方法。(Btn.Click += f(…))

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。