欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c# 委托和事件實(shí)例學(xué)習(xí)

 更新時(shí)間:2009年01月30日 18:28:28   作者:  
今天把委托和事件研究了一個(gè),winForm環(huán)境下,一般的小例子都是字符界面,我為了運(yùn)用一下,寫了winForm
Common.cs:
復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
namespace DelegateAndEvent.App_Code
{
public class Common
{
//定義全局變量.
public static string txt = "";
#region 定義方法
public string HelloCSharp(string name)
{
txt += "hello " + name;//這樣做是為了看到委托可以執(zhí)行多個(gè)方法.
return "hello " + name;
}
public string HiCSharp(string name)
{
txt += "hi " + name;
return "hi " + name;
}
#endregion
#region 定義委托
//定義委托和定義方法類似,區(qū)別是加個(gè)delegate.去掉方法體,只寫方法簽名.
public delegate string SayHi(string name);
//委托可以像普通變量一樣使用.區(qū)別在于可以把多個(gè)方法賦給委托.
public SayHi dlgt1, dlgt2;
//使用委托
public void useDelegate(string name, SayHi sayHi)
{
sayHi(name);
}
#endregion
#region 事件
//聲明事件
public event SayHi hiEvent;
//觸發(fā)事件
public void causeEvent()
{
hiEvent += HelloCSharp;
hiEvent += HiCSharp;
if (hiEvent != null)
{
hiEvent("crane");
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace DelegateAndEvent.App_Code
{
public class Common
{
//定義全局變量.
public static string txt = "";
#region 定義方法
public string HelloCSharp(string name)
{
txt += "hello " + name;//這樣做是為了看到委托可以執(zhí)行多個(gè)方法.
return "hello " + name;
}
public string HiCSharp(string name)
{
txt += "hi " + name;
return "hi " + name;
}
#endregion
#region 定義委托
//定義委托和定義方法類似,區(qū)別是加個(gè)delegate.去掉方法體,只寫方法簽名.
public delegate string SayHi(string name);
//委托可以像普通變量一樣使用.區(qū)別在于可以把多個(gè)方法賦給委托.
public SayHi dlgt1, dlgt2;
//使用委托
public void useDelegate(string name, SayHi sayHi)
{
sayHi(name);
}
#endregion
#region 事件
//聲明事件
public event SayHi hiEvent;
//觸發(fā)事件
public void causeEvent()
{
hiEvent += HelloCSharp;
hiEvent += HiCSharp;
if (hiEvent != null)
{
hiEvent("crane");
}
}
#endregion
}
}

MainFrm.cs:
復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DelegateAndEvent.App_Code;
namespace DelegateAndEvent
{
public partial class MainFrm : Form
{
Common common = new Common();
public MainFrm()
{
InitializeComponent();
}
private void btnOk_Click(object sender, EventArgs e)
{
//this.lblShow.Text += common.HelloCSharp("tree");
//測(cè)試委托
common.dlgt1 = common.HelloCSharp;//只寫方法簽名,不加()
common.dlgt1 += common.HiCSharp;//雖然兩個(gè)方法都調(diào)用了,但是返回值只返回最后一次調(diào)用的值.
//this.lblShow.Text += common.dlgt1("tree");//使用委托就像使用方法一樣.
//this.lblShow.Text = Common.txt;
//用委托做參數(shù)
//common.useDelegate("tree", common.dlgt1);
//this.lblShow.Text = Common.txt;
//事件
/*這里的問題是不能用common.hiEvent();這樣引用.
原因是需要在這個(gè)類里定義一個(gè)事件變量.
*/
common.causeEvent();
this.lblShow.Text = Common.txt;
}
}
}

相關(guān)文章

最新評(píng)論