您的位置:首页 > 编程语言 > C#

C#中关于委托和事件的示例代码

2010-07-05 16:35 501 查看
示例1:匿名方法

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace ConsoleApplication1
{
class Program
{
delegate string delegateTest(string val);

static void Main(string[] args)
{
string mid = ", middle part,";

delegateTest d = delegate(string param)
{
param += mid;
param += " and this was added to the string.";
return param;
};

Console.WriteLine(d("Start of string"));

}
}
}


优点:使用匿名方法建立委托可减少系统开销,降低代码复杂性。

在使用匿名方法时必须遵循两个规则:

1.在 匿名方法中不能使用跳转语句跳到改匿名方法的外部,反之亦然:匿名方法外部的跳转语句不能跳到该匿名防范的内部。

2.在匿名方法内部不能访问不安全的代码。另外,也不能访问在匿名方法外部使用的ref和out参数,但可以使用在匿名方法外部定义的其他变量。

示例2:简单委托示例

using System;

namespace SimpleDelegate
{
delegate double DoubleOp(double x);

class MainEntryPoint
{
static void Main()
{
DoubleOp [] operations =
{
new DoubleOp(MathsOperations.MultiplyByTwo),
new DoubleOp(MathsOperations.Square)
};

for (int i=0 ; i<operations.Length ; i++)
{
Console.WriteLine("Using operations[{0}]:", i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
Console.WriteLine();
}
Console.ReadLine();
}

static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
double result = action(value);
Console.WriteLine("Value is {0}, result of operation is {1}", value, result);
}
}

class MathsOperations
{
public static double MultiplyByTwo(double value)
{
return value*2;
}

public static double Square(double value)
{
return value*value;
}
}
}


以下代码将示例2改写成匿名方法形式:

using System;

namespace SimpleDelegate
{
delegate double DoubleOp(double x);

class MainEntryPoint
{
static void Main()
{

DoubleOp multByTwo = delegate(double value) { return value * 2; };
DoubleOp square = delegate(double value) { return value * value; };

DoubleOp [] operations = { multByTwo, square };

for (int i=0 ; i<operations.Length ; i++)
{
Console.WriteLine("Using operations[{0}]:", i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
Console.WriteLine();
}
Console.ReadLine();
}

static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
double result = action(value);
Console.WriteLine("Value is {0}, result of operation is {1}", value, result);
}
}
}


示例3:冒泡排序

using System;

namespace BubbleSorter
{
delegate bool CompareOp(object lhs, object rhs);

class MainEntryPoint
{
static void Main()
{
Employee [] employees =
{
new Employee("Bugs Bunny", 20000),
new Employee("Elmer Fudd", 10000),
new Employee("Daffy Duck", 25000),
new Employee("Wiley Coyote", (decimal)1000000.38),
new Employee("Foghorn Leghorn", 23000),
new Employee("RoadRunner'", 50000)};
CompareOp employeeCompareOp = new CompareOp(Employee.RhsIsGreater);
BubbleSorter.Sort(employees, employeeCompareOp);

for (int i=0 ; i<employees.Length ; i++)
Console.WriteLine(employees[i].ToString());
Console.ReadLine();
}
}

class Employee // : object
{
private string name;
private decimal salary;

public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}

public override string ToString()
{
return string.Format(name + ", {0:C}", salary);
}

public static bool RhsIsGreater(object lhs, object rhs)
{
Employee empLhs = (Employee) lhs;
Employee empRhs = (Employee) rhs;
return (empRhs.salary > empLhs.salary) ? true : false;
}
}

class BubbleSorter
{
static public void Sort(object [] sortArray, CompareOp gtMethod)
{
for (int i=0 ; i<sortArray.Length ; i++)
{
for (int j=i+1 ; j<sortArray.Length ; j++)
{
if (gtMethod(sortArray[j], sortArray[i]))
{
object temp = sortArray[i];
sortArray[i] = sortArray[j];
sortArray[j] = temp;
}
}
}
}
}
}


注意:冒泡排序只适合一小组数字的排序,对于大量数字(超过10个),应该选用更高效的排序算法。

示例4:多播委托

using System;

namespace MulticastDelegate
{
delegate void DoubleOp(double value);

class MainEntryPoint
{
static void Main()
{
DoubleOp operations = new DoubleOp(MathsOperations.MultiplyByTwo);
operations += new DoubleOp(MathsOperations.Square);

ProcessAndDisplayNumber(operations, 2.0);
ProcessAndDisplayNumber(operations, 7.94);
ProcessAndDisplayNumber(operations, 1.414);
Console.WriteLine();
Console.ReadLine();
}

static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
Console.WriteLine("/nProcessAndDisplayNumber called with value = " + value);
action(value);
}
}

class MathsOperations
{
public static void MultiplyByTwo(double value)
{
double result = value*2;
Console.WriteLine("Multiplying by 2: {0} gives {1}", value, result);
}

public static void Square(double value)
{
double result = value*value;
Console.WriteLine("Squaring: {0} gives {1}", value, result);
}
}
}


可见:多播委托中同样识别+=,-=操作符(+表示从委托中增加方法调用,-表示从委托中删除方法调用)。

事件(页面代码省去):

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;

namespace SimpleEvent
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnOne;
private System.Windows.Forms.Button btnTwo;
private System.Windows.Forms.Label lblInfo;
private System.Windows.Forms.Button btnRaise;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

BusEntity _busEntity = new BusEntity();

public delegate void ActionEventHandler(object sender, ActionCancelEventArgs ev);
public static event ActionEventHandler Action;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

btnOne.Click += new EventHandler(Button_Click);
btnTwo.Click += new EventHandler(Button_Click);
btnTwo.Click += new EventHandler(btnTwo_Click);

btnRaise.Click += new EventHandler(btnRaise_Click);

}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnOne = new System.Windows.Forms.Button();
this.btnTwo = new System.Windows.Forms.Button();
this.lblInfo = new System.Windows.Forms.Label();
this.btnRaise = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnOne
//
this.btnOne.Location = new System.Drawing.Point(104, 88);
this.btnOne.Name = "btnOne";
this.btnOne.TabIndex = 0;
this.btnOne.Text = "Button 1";
//
// btnTwo
//
this.btnTwo.Location = new System.Drawing.Point(104, 120);
this.btnTwo.Name = "btnTwo";
this.btnTwo.TabIndex = 1;
this.btnTwo.Text = "Button 2";
//
// lblInfo
//
this.lblInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.lblInfo.Location = new System.Drawing.Point(40, 40);
this.lblInfo.Name = "lblInfo";
this.lblInfo.Size = new System.Drawing.Size(208, 23);
this.lblInfo.TabIndex = 2;
this.lblInfo.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// btnRaise
//
this.btnRaise.Location = new System.Drawing.Point(104, 160);
this.btnRaise.Name = "btnRaise";
this.btnRaise.TabIndex = 3;
this.btnRaise.Text = "Raise Event";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 203);
this.Controls.Add(this.btnRaise);
this.Controls.Add(this.lblInfo);
this.Controls.Add(this.btnTwo);
this.Controls.Add(this.btnOne);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void Button_Click(object sender, EventArgs e)
{
lblInfo.Text = ((Button)sender).Text + " was pressed";
}

private void btnTwo_Click(object sender, EventArgs e)
{
MessageBox.Show("This only happens in Button 2 click event");
}

private void btnRaise_Click(object sender, EventArgs e)
{
ActionCancelEventArgs cancelEvent = new ActionCancelEventArgs();
OnAction(this, cancelEvent);
if(cancelEvent.Cancel)
lblInfo.Text = cancelEvent.Message;
else
lblInfo.Text = _busEntity.TimeString;
}

protected void OnAction(object sender, ActionCancelEventArgs ev)
{
if(Action != null)
Action(sender, ev);
}

}

public class ActionCancelEventArgs : System.ComponentModel.CancelEventArgs
{

string _msg = "";

public ActionCancelEventArgs()  : base()  {}

public ActionCancelEventArgs(bool cancel) : base(cancel)  {}

public ActionCancelEventArgs(bool cancel, string message) : base(cancel)
{
_msg = message;
}

public string Message
{
get {return _msg;}
set {_msg = value;}
}
}
}


BusEntity.cs文件:

using System;
using System.IO;
using System.ComponentModel;

namespace SimpleEvent
{
/// <summary>
/// Summary description for BusEntity.
/// </summary>
public class BusEntity
{

string _time = "";

public BusEntity()
{
//Form1.Action += new Form1.ActionEventHandler(EventManager_Action);
}

private void EventManager_Action(object sender, ActionCancelEventArgs ev)
{
ev.Cancel = !DoActions();
if(ev.Cancel)
ev.Message = "Wasn't the right time.";
}

private bool DoActions()
{
bool retVal = false;
DateTime tm = DateTime.Now;

if(tm.Second < 30)
{
_time = "The time is " + DateTime.Now.ToLongTimeString();
retVal = true;
}
else
_time = "";

return retVal;

}

public string TimeString
{
get {return _time;}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: