.Net 's delegates and events

7 篇文章 0 订阅
4 篇文章 0 订阅

.Net 's delegates and events

                                                                                                   --jenry

一、Delegates and Events
1.Multicast Delegates
2.Events
3.when to use delegates,Events,and interfaces

Delegate Scenario
Declaring a Delegate
Instantiating a Delegate
Calling a Delegate

一、Declaring a Delegate
A Delegate Declaration Defines a Type That Encapsulates a Method with a Particular Set of

Arguments and Return Type
代理相当于C++下面的函数指针。一个指针指向一个函数,而代理可以同时连接(指向)多个函数(函数链表


// declares a delegate for a method that takes a single
//  argument of type string and has a void return type
delegate void MyDelegate1(string s);
二、Instantiating a Delegate
在C#声明一个代理,相当创建了一个类,可以被实例化。
A Delegate Object Is Created with the new Operator
Delegate Objects Are Immutable
// instantiating a delegate to a static method Hello //   in the class MyClass MyDelegate1 a =

new MyDelegate1(MyClass.Hello); // instantiating a delegate to an instance method //  AMethod in

object p MyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod);
三、Calling a Delegate
Use a Statement Containing:
The name of the delegate object
Followed by the parenthesized arguments to be passed to the delegate
// given the previous delegate declaration and
//  instantiation, the following invokes MyClass'
//  static method Hello with the parameter "World"
a("World");
四、using Delegates
example:
//declare
public delegate void MyDelegate(string s);
public static void HelloWorld(string s)
{
 MessageBox.show("HelloWorld ,"+ s);
}

public static void ThankYou(string s)
{
 MessageBox.show("Thank you, "+ s);
}
private void Button1_Click(object sender,System.EventArg e)
{
 MyDelegate1 a = new MyDelegate(this.HelloWorld);
 //a = a + b;构造一个函数链表,顺序执行
 MyDelegate1 b = new MyDelegate(this.ThankYou);
 a("zhang shang");
}
五、Multicast Delegate Scenario
1.Single vs. Multicast Delegates
All Delegates Have an Invocation List of Methods That Are Executed When Their Invoke Method is

Called
Single-Cast Delegates: Derived Directly From System.MulticastDelegate
Invocation list contains only one method
2.Multicast Delegates
Multicast Delegates: Derived from System.MulticastDelegate
Invocation list may contain multiple methods
Multicast delegates contain two static methods to add and remove references from invocation

list: Combine and Remove
Use GetInvocationList to Obtain an Invocation List as an Array of Delegate References
Use a Delegate’s Target and Method Properties to Determine:
Which object will receive the callback
Which method will be called
六、Creating and Invoking Multicast Delegates
// assign to c the composition of delegates a and b
c = (MyDelegate2)Delegate.Combine(a, b);  
// assign to d the result of removing a from c
d = (MyDelegate2)Delegate.Remove(c, a);    
// Iterate through c's invocation list
//  and invoke all delegates except a Delegate[]
DelegateList = c.GetInvocationList();
for (int i = 0; i < DelegateList.Length; i++)
{  
if (DelegateList[i].Target != a)
 {
  ((MyDelegate2) DelegateList[i])();
 }
}
七、C# Language-Specific Syntax
C# Delegates That Return Void Are Multicast Delegates
In C#, Use the + and - Operators to Add and Remove Invocation List Entries
Less verbose than Combine and Remove methods
MyDelegate a, b, c, d;
a = new MyDelegate(Foo);
b = new MyDelegate(Bar);
c = a + b;  // Compose two delegates to make another
d = c - a;  // Remove a from the composed delegate
a += b; // Add delegate b to a's invocation list
a -= b; // Remove delegate b from a's list
八、Delegate Details
A Delegate Declaration Causes the Compiler to Generate a New Class
In fact,a delegate class inherits the  System.MulticastDelegate class
// delegate void MyDelegate3(string val);
class MyDelegate3 : System.MulticastDelegate
{
 public MyDelegate3(object obj, methodref mref)  : base (obj, mref)
 { //... }
 public void virtual Invoke(string val)
 { //... }
};
九、Events
实质就是一个delegate的instance
Event Scenario
Declaring an Event
Connecting to an Event
Raising an Event
.NET Framework Guidelines

1.Event Scenario

2.Declaring an Event

Declare the Delegate Type for the Event
Declare the Event
Like the field of delegate type preceded by an event keyword
// MouseClicked delegate declared
public delegate void MouseClickedEventHandler();
public class Mouse
{
 // MouseClicked event declared
 public static event MouseClickedEventHandler MouseClicked;
 //...
}
3.Connecting to an Event
Connect by Combining Delegates
Disconnect by Removing Delegates
// Client’s method to handle the MouseClick event
private void MouseClicked() { //...
}
//...
// Client code to connect to MouseClicked event
Mouse.MouseClicked += new  MouseClickedEventHandler(MouseClicked);
// Client code to break connection to MouseClick event
Mouse.MouseClicked -= new  MouseClickedEventHandler(MouseClicked);
4.Raising an Event
Check Whether Any Clients Have Connected to This Event
 If the event field is null, there are no clients
Raise the Event by Invoking the Event’s Delegate
if (MouseClicked != null) MouseClicked();

Name Events with a Verb and Use Pascal Casing
Use “Raise” for Events, Instead of “Fire”
Event Argument Classes Extend System.EventArgs
Event Delegates Return Void and Have Two Arguments
Use a Protected Virtual Method to Raise Each Event
5..NET Framework Guidelines
public class SwitchFlippedEventArgs : EventArgs { //... }
public delegate void SwitchFlippedEventHandler( object sender, SwitchFlippedEventArgs e);
public event SwitchFlippedEventHandler SwitchFlipped;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值