Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is a C # delegation?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is C# delegate". In daily operation, I believe that many people have doubts about what C# delegate is. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubt of "what is C# delegate?" Next, please follow the editor to study!

Start with the example

Suppose the user login module of a system has the following code

Class User {public string Name {get; set;} public string Password {get; set;}} class UserService {public void Register (User user) {if (user.Name = = "Kirin") {Log ("Registration failed and already contains a user named" + user.Name + ") } else {Log ("registered successfully!") ;} privte void Log (string message) {Console.WriteLine (message);}}

The UserService class encapsulates the logic of user login and prints different log contents to the console according to different login situations. When the program closes, the log naturally disappears.

The code for the client is

Class Program {static void Main (string [] args) {User user = new User {Name = "Kirin", Password = "123"}; UserService service = new UserService (); service.Register (user); Console.ReadLine ();}}

Use policy mode

However, this kind of design certainly can not meet the needs of users, and users certainly want to be able to view previous log records, not just the content after the program is opened. If we just modify the implementation of the Log method, what should we do if the user's requirements change again? Do you want to modify the Log method endlessly?

Since the way logging is the root cause of change, we naturally want to encapsulate it. We create an interface called ILog.

Interface ILog {void Log (string message);}

And create two classes that implement ILog, ConsoleLog and TextLog, to output the log contents to the console and the text file, respectively.

Class ConsoleLog: ILog {public void Log (string message) {Console.WriteLine (message);}} class TextLog: ILog {public void Log (string message) {using (StreamWriter sw = File.AppendText ("log.txt")) {sw.WriteLine (message); sw.Flush (); sw.Close () }}}

Add a property of type ILog LogStrategy to the UserService class.

Class UserService {public ILog LogStrategy {get; set;} public UserService () {LogStrategy = new ConsoleLog ();} public void Register (User user) {if (user.Name = = "Kirin") {LogStrategy.Log ("Registration failed and already contains a user named" + user.Name + ") } else {LogStrategy.Log ("registered successfully!") ;}

The client code changes to the following form.

Class Program {static void Main (string [] args) {User user = new User {Name = "Kirin", Password = "123"}; UserService service = new UserService {LogStrategy = new TextLog ()}; service.Register (user); Console.ReadLine ();}}

When declaring UserService, you can also set LogStrategy to TextLog. In this way, when UserService performs logical processing, the LogStrategy used is TextLog, and the log is output to a text file.

What are we doing? We're refactoring. What is the result of refactoring? The result of refactoring is the implementation of a simple policy pattern.

Use delegation

However, the strategy model still can not meet the needs of customers, this is why?

1. Users may want to customize the implementation of Log. Of course, you can implement your own logging method by extending ILog at the client code. Such as

Class TextBoxLog: ILog {private TextBox textBox; public TextBoxLog (TextBox textBox) {this.textBox = textBox; this.textBox.Multiline = true;} public void Log (string message) {textBox.AppendText (message); textBox.AppendText (Environment.NewLine);}}

But is this scheme too complicated? If users want to display on ListView or other controls, do they need to create new classes one by one? And is this implementation too tightly coupled with the client? For example, if users want to display different contents such as log content, time, source, and so on, in various columns of ListView, is it difficult to reuse ListView hard-coding in ListViewLog?

two。 Users may want to use multiple logging methods at the same time. For example, output logs to the console, text files, client controls, and event viewers at the same time. Of course you can maintain a List in UserService, but at this time UserService has too many responsibilities and obviously violates SRP.

The following introduces the protagonist of this article: delegation.

Let's start by creating a delegate named Log, which takes a parameter of type string.

Public delegate void Log (string message)

Then add a property of Log delegate type LogDelegate to the UserService class.

Class UserService {public Log LogDelegate {get; set;} / / … }

On the client side, we declare two static methods directly, both of which contain a parameter of type string and have no return value.

Static void LogToConsole (string message) {Console.WriteLine (message);} static void LogToTextFile (string message) {using (StreamWriter sw = File.AppendText ("log.txt")) {sw.WriteLine (message); sw.Flush (); sw.Close ();}}

The code that declares UserService on the client becomes

Static void Main (string [] args) {User user = new User {Name = "Kirin", Password = "123"}; UserService service = new UserService (); service.LogDelegate = LogToConsole; service.LogDelegate + = LogToTextFile; service.Register (user); Console.ReadLine ();}

When constructing a delegate, we can also use anonymous methods and Lambda expressions, which are described in detail in Lao Zhao's article.

There is a clear description in MSDN of when to use delegates and when to use interfaces (that is, policy mode):

Use delegates in the following situations:

◆ when using the event design pattern.

◆ when encapsulating static methods is available.

◆ when the caller does not need to access other properties, methods, or interfaces in the object that implements the method.

◆ needs a convenient combination.

◆ when the class may need multiple implementations of the method.

Use an interface in the following situations:

◆ when there is a set of related methods that may be called.

◆ when the class only needs a single implementation of the method.

◆ when a class that uses an interface wants to cast the interface to another interface or class type.

◆ when the method being implemented is linked to the type or identity of the class: for example, a comparison method.

You may find the above example a bit far-fetched in terms of delegates and interfaces, but in fact it is sometimes difficult to choose whether to use interfaces or delegates. There is no delegate in Java, but all situations where a delegate applies can also be implemented using an interface that contains a single method. To some extent, a delegate is a lightweight implementation of an interface (only a single method is defined), which is more flexible and convenient.

At this point, the study of "what is the delegation of C#" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report