C# warm up

來源:互聯網
上載者:User

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 );   


 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.