Value of number: 175
Delegate objects can be composed of other delegates with the "+" operator. A delegate is composed of two Delegates that are composed of that word. Only the same type delegates can be formed. The "-" operator can be used to remove a delegate from a combined delegate.
Using this feature of delegates, you can create a summon list of methods that will be called when that delegate is summoned. This is called Multicasting of a Delegate. The following example program illustrates Multicasting of a Delegate in C #:
using System ; delegate int NumberChanger ( int n ); namespace QTMCSharp { class Tester { static int num = 10 ; public static int AddNum ( int p ) { num += p ; return num ; } public static int MultNum ( int q ) { num *= q ; return num ; } public static int getNum () { return num ; } static void Main ( string [] args ) { //tạo các thể hiện delegate NumberChanger nc ; NumberChanger nc1 = new NumberChanger ( AddNum ); NumberChanger nc2 = new NumberChanger ( MultNum ); nc = nc1 ; nc += nc2 ; //gọi multicast nc ( 5 ); Console . WriteLine ( "Giá trị của số: {0}" , getNum ()); Console . ReadKey (); } } }
The results when running the above program will be as follows:
Value of number: 75
The following example will illustrate how to use delegates in C #. The delegate with the name printString can be used to reference the input method as a string and not return anything.
We use this delegate to call two methods: the first method prints the string to Console, and the second method prints it to a File.
using System ; using System . IO ; namespace QTMCsharp { class TestCsharp { static FileStream fs ; static StreamWriter sw ; // khai báo delegate public delegate void printString ( string s ); // phương thức thứ nhất để in trên console public static void WriteToScreen ( string str ) { Console . WriteLine ( "Chuỗi la: {0}" , str ); } //phương thức thứ hai để ghi dữ liệu vào file public static void WriteToFile ( string s ) { fs = new FileStream ( "c:message.txt" , FileMode . Append , FileAccess . Write ); sw = new StreamWriter ( fs ); sw . WriteLine ( s ); sw . Flush (); sw . Close (); fs . Close (); } // phương thức này nhận delegate làm tham số và // sử dụng nó để gọi các phương thức nếu cần. public static void sendString ( printString ps ) { ps ( "TipsMake.com" ); } static void Main ( string [] args ) { Console . WriteLine ( "Ví dụ về Delegate C#:" ); Console . WriteLine ( "--------------------------" ); printString ps1 = new printString ( WriteToScreen ); printString ps2 = new printString ( WriteToFile ); sendString ( ps1 ); sendString ( ps2 ); Console . ReadKey (); } } }
Compile and run the C # program to see the results.
Example of Delegate C #:
--------------------------
The series is: TipsMake.com
According to Tutorialspoint
Previous article: Indexer in C #
Next article: Events (Event) in C #