C# warm up

Drop C# for a long time, just warm up. 


Delegate

 

Official definition 

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate. 

 

Delegate types are derived from the Delegate class in the .NET Framework. 

 

Along with the static DelegateMethod shown previously, we now have three methods that can be wrapped by a Del instance.

A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's list of methods—the invocation list—simply requires adding two delegates using the addition or addition assignment operators ('+' or '+='). For example:

 


MethodClass obj = new MethodClass(); 
Del d1 = obj.Method1; 
Del d2 = obj.Method2; 
Del d3 = DelegateMethod; 

//Both types of assignment are valid. 
Del allMethodsDelegate = d1 + d2; 

 

allMethodsDelegate
 += d3;

 

 

At this point allMethodsDelegate contains three methods in its invocation list—Method1Method2, and DelegateMethod. The original three delegates, d1d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. When any of the methods throws an exception that is not caught within the method, that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called. If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked. To remove a method from the invocation list, use the decrement or decrement assignment operator ('-' or '-='). 

多个委托:顺序调用,参数会分别传入每个委托;内容的修改会传递至下一个委托;有返回值时,返回最后一个委托的返回值。

delegate: 声明时用的关键字,小写

// Declares a delegate for a method that takes in an int and returns a String.

public delegate String myMethodDelegate( int myInt );   


 

 

posted @ 2011-11-02 18:21  Carrot  阅读(256)  评论(0编辑  收藏  举报