Delegate in C #
Delegate in C # is similar to pointers to functions, in C or in C ++.Delegate is a reference type variable that contains references to a method. That reference can be changed at runtime.
In particular, delegates are used to deploy call events and call-back methods. All delegates are implicitly derived from the System.Delegate class in C #.
Declaring the Delegate in C #
Delegate declaration in C # defines the methods that can be referenced by Delegate. A Delegate can refer to a method, which has the same sign as Delegate.
For example, consider delegate following:
public delegate int MyDelegate ( string s );
The above delegate can be used to reference any method that has a single string parameter and returns a variable of type int .
The syntax for declaring delegates in C # is:
delegate < ki ể u_tr ả _v ề> < t ê n_delegate > < danh_s á ch_tham_s ố>
Initialize Delegate in C #
When delegate type is declared, delegate object must be created with new keyword and associated with a specific method. When creating a delegate, the parameter passed to the new expression is written similar to a method call, but there is no parameter to that method. For example:
public delegate void printString ( string s ); . printString ps1 = new printString ( WriteToScreen ); printString ps2 = new printString ( WriteToFile );
The following example illustrates how to declare, initialize, and use delegates to reference methods, taking integer parameters and returning an integer value.
using System ; delegate int NumberChanger ( int n ); namespace DelegateAppl { class TestDelegate { 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 thể hiện delegate NumberChanger nc1 = new NumberChanger ( AddNum ); NumberChanger nc2 = new NumberChanger ( MultNum ); //gọi phương thức sử dụng đối tượng delegate nc1 ( 25 ); Console . WriteLine ( "Giá trị của số: {0}" , getNum ()); nc2 ( 5 ); Console . WriteLine ( "Giá trị của số: {0}" , getNum ()); Console . ReadKey (); } } }
When running the above code you will get the following result:
Value of number: 35
Value of number: 175
Multicast (multidirectional) a Delegate in C #
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
How to use Delegate in C #
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 #
You should read it
- Does the laptop burn itself?
- Generic in C #
- Event (Event) in C #
- Distribute file access with chmod command
- Fix Bluestacks Initializing load errors permanently on the main screen
- COVID-19 prevention medical declaration application has been launched, integrating the feature to reflect suspected cases to the regulatory agency.
- How to install and configure Java tax declaration online
- Syntax and Selector in CSS
May be interested
- AZ word about eggs in Pokemon Gothere are many different pokemon eggs that can hatch into many pokemon, but to make these eggs hatch into pokemon, you will have to perform some tasks. each player begins with an egg incubator, which allows the user to incubate an egg after performing certain steps, gps and pedometer tracking on the mobile device of you and the game.
- Things you didn't know about 26 types of Pokéball - Part 1pokéball is the most important item in pokémon go, allowing gamers to quickly catch pokémon back to their team. the higher the pokéball, the more effective the ability to catch pokémon.
- 10 tips to help you become a great Pokemon trainerin the article below, tipsmake.com will introduce to you some tips to easily become a great trainer in this pokemon go game offline ...
- How to use GoChat application in Pokémon GOpokémon go has become a very hot phenomenon since its debut. any information or tricks related to the game are read and applied by players during the process of catching pokémon. and the gochat chat app for pokémon go players brings space to capture pokémon much more interesting.
- How to play Pokemon GO in Landscape Mode on the iPhonealthough players can play pokemon go in portrait mode. however, if you want to watch and play games on a large and eye-catching screen, players can switch to playing games in landscape mode.
- The secret to controlling Pokemon Go employees at workthese days, hr managers are faced with an extremely painful problem that is the status of priority employees playing pokemon go more than work. this has caused a small impact on productivity and efficiency.
- Check out the 'buffalo' Pokémon in Pokémon Goeach type of pokemon has hp, cp, ability to attack and endure differently. based on these indicators, players can determine as well as choosing the most powerful pokemon for their offensive tactics.
- Sitting home can also locate Pokemon around, do you believe it?the tightening of the niantic developers' rules to prevent players from abusing the support tools also brings annoyance, such as those who have no conditions to move much, go away, it is hard to know. get the location of the pokemon around the area they live in
- 5 undeniable benefits when playing Pokemon Goget to know many new people, breathe fresh air, relieve stress, increase concentration thanks to going out for a walk .... are compelling reasons to force you to try pokemon go now .
- Want to earn the fastest Pokécoins in Pokémon Go? So don't miss this article!pokécoins in pokémon go play the role of buying items in the store. the more coins you earn, the more likely you are to buy more items. to earn pokécoins, players will have to complete certain tasks or buy real money.