一、代理Delegate
委托实际上是定义一类型的委托,委托类型代表的是方法的返回类型和参数表。委托代表的是具有相同参数列表和返回类型的任何方法。
using System;
public delegate double DelegateCompute(double x);
namespace MyDelegateDemo
{
public class MoneyCompute
{
public static double Compute(double t,DelegateCompute dc)
{ return dc(t);}
}
public class Class1
{
public static double Low(double t){ return 0.02 * t;}
static void Main()
{
DelegateCompute dc = new DelegateCompute(Class1.Low);
double resutl = MoneyCompute.Compute(100,dc);
}
}
}
多播委托是引用多个方法的委托,它连续调用每个方法。但它们必需是同类型的,返回类型是Void,不能带输出参数。多用于事件模型。
using
System;
public
delegate
void
Message();
namespace
WindowsApplication4{
public
class
Messages {
public
Messages() { }
public
static
void
Greeting() { Console.WriteLine(
"
Welcome to Webcast and MSDN China
"
); }
public
static
void
DateAndTime() { Console.WriteLine(DateTime.Now.ToLongDateString()); }
public
static
void
Feedback() { Console.WriteLine(
"
Your feedback are very important for us
"
); } }
public
class
Class1 {
private
void
View_Click(
object
sender, System.EventArgs e) { Message msg; msg
=
new
Message(Messages.Greeting); msg
+=
new
Message(Messages.DateAndTime); Message msg2
=
new
Message(Messages.Feedback); msg
+=
msg2; msg(); } }}
二、事件Event
事件的作用是把事件源和事件处理程序结合起来。
//
NameListEventArgs.cs
using
System;
public
delegate
void
NameListEventHandler(
object
source, WindowsApplication5.NameListEventArgs args);
namespace
WindowsApplication5
{ public class NameListEventArgs : EventArgs { string name; int count; public NameListEventArgs() { } public NameListEventArgs(string name, int count) { this.name = name; this.count = count; } public string Name { get { return name; } } public int Count { get { return count; } } }}
//
NameList.cs
using
System;
using
System.Collections;
namespace
WindowsApplication5
{ public class NameList { ArrayList list; public event NameListEventHandler nameListEvent; public NameList() { list = new ArrayList(); } public void Add(string name) { list.Add(name); if(nameListEvent != null) { nameListEvent(this, new NameListEventArgs(name, list.Count)); } } }}
//
Form.cs
private
void
button1_Click(
object
sender, System.EventArgs e)
{ NameList names =new NameList(); names.nameListEvent += new NameListEventHandler(NewName); names.nameListEvent += new NameListEventHandler(CurrentCount); names.Add("MSDN"); names.Add("Webcast"); }
public
static
void
NewName(
object
source, NameListEventArgs args)
{ Console.WriteLine(args.Name + "was added to the list"); }
public
static
void
CurrentCount(
object
source, NameListEventArgs args)
{ Console.WriteLine("list currently has " + args.Count + " items."); }
转载于:https://www.cnblogs.com/hotsoho.net/articles/240748.html
相关资源:Modern C#系列课程(2):类, 组和名称空间