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

How to parse the confusing delegation and interface in. Net

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

Share

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

How to parse the confusing delegation and interface in .NET, many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

Yesterday, I was discussing the issue of delegation and interface with a friend. At first, I thought it was incredible. How could the concepts of these two things be confused? To confuse is also interface and abstract class, delegate and event confusion! But with an example of mine, I immediately realized that it is very likely that because of the example I am going to show, many friends have confused the use of delegation and interface. So I want to try to explain the concept and use of delegate and interface through this article, but there is a big difference between them.

Entrust:

A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can call a method through a delegate instance.

Delegates are used to pass methods as parameters to other methods. An event handler is a method called by a delegate. You can create a custom method that can be called by a class (such as a Windows control) when a specific event occurs.

Delegation has the following characteristics:

Delegates are similar to C++ function pointers, but they are type safe.

Delegates allow methods to be passed as parameters.

Delegates can be used to define callback methods.

Delegates can be linked together; for example, multiple methods can be called on an event.

The method does not have to exactly match the delegate signature. For more information, see using variants (C # and Visual Basic) in delegates.

Version 2.0 of C # introduces the concept of anonymous methods, which allow code blocks to be passed as parameters instead of individually defined methods. C # 3.0 introduces Lambda expressions, which allow you to write inline code blocks more succinctly. Both anonymous methods and Lambda expressions (in some contexts) can be compiled to delegate types. These functions are collectively referred to as anonymous functions. For more information about Lambda expressions, see Anonymous Functions (C # Programming Guide).

Interface:

An interface describes a set of related functions that can belong to any class or structure. An interface can consist of methods, properties, events, indexers, or any combination of these four member types. The interface cannot contain fields. Interface members must be public.

When a class or structure inherits an interface, it means that the class or structure provides an implementation for all members defined by the interface. The interface itself does not provide any functionality that a class or structure can inherit in a way that inherits the functionality of the base class. However, if the base class implements the interface, the derived class inherits the implementation.

Classes and structures can inherit interfaces in a similar way that classes inherit from base classes or structures, with two exceptions:

A class or structure can inherit multiple interfaces.

When a class or structure inherits an interface, it inherits only the method name and signature, because the interface itself does not contain an implementation.

The interface has the following properties:

An interface is similar to an abstract base class: any non-abstract type that inherits an interface must implement all members of the interface.

The interface cannot be instantiated directly.

Interfaces can contain events, indexers, methods, and properties.

The interface does not contain an implementation of the method.

Classes and structures can inherit from multiple interfaces.

The interface itself can inherit from multiple interfaces.

The text begins.

In writing these words, I familiarize myself with the above concepts again in case I confuse myself. Therefore, it is not suitable for the masses. Please withdraw as soon as possible. In addition, if you come out of the confusion after reading the above definitions and features, you can also try to move on.

First of all, with regard to the use of delegates, we can use:

The following is a code snippet:

Public int Calculate (Func del) {int a = 1, b = 2; return del (a, b);}

We can change the result of the whole method by passing different Func.

The following is a code snippet:

Public int Add (int a, int b) {return a + b;} public int Sub (int a, int b) {return a-b;} / / call the method as follows: public void TestMethod () {int result = Calculate (Add); / / the result is 3 int anotherResult = Calculate (Sub); / / the result is-1}

First of all, I have determined the values of 2 numbers in the Calculate method and are included in the method. When outputting the result, it is obvious that the delegate passed is different, and the result is also different. We use delegates to change the execution of a method. We can not only change the content of the method, but also do something (such as logging) while executing the method.

Well, maybe what you think is easy to confuse the two is.. It is easier for me to give an example.

The following is a code snippet:

Public interface ICal {int Calculate (int a, int b);} / / has multiple classes that implement the ICal interface. Public class Add: ICal {public int Calculate (int a, int b) {return a + b;}} public class Sub: ICal {public int Calculate (int a, int b) {return a-b;}} / then get different methods public static void Main () {ICal cal = new Add (); / / ICal=new Sub (); Console.Write (cal.Calculate (1, 2));} by calling different classes

To explain, through the above example we can know that after creating an interface ICal with computing function (Calculate), there are two concrete classes with computing function, namely Add and Sub. In order to get the result, we create a "pit" that needs to have computing function, and give the class Add (or Sub) that can match this "pit", and * * call the result of Calculate from this pit.

Does it seem to make sense? Well, then I have to at least make you feel that there is a scope of application! Take a look at the following example.

For example, there is an array of Person class arr. At this time, we can achieve the sorting of arr by delegating. But how does the system know which of the two Person is at the front and which is at the back? At this point we can pass in a delegate to tell the system the size of the Peron class.

The following is a code snippet:

Arr.Sort (p = > {p.ID})

The lambda expression means to throw the Sort method a sorted Key (this key can be compared in size), so the Sort can compare according to this key. What about through the interface? First I have to create a class that inherits from IComparer, and I'll inherit it myself.

Well, it was supposed to be troublesome:

The following is a code snippet:

Private int SortDelegate (Person p) {return p.ID;} public void TestMethod () {arr.Sort (new Func (SortDelegate));}

But we have to admit the convenience that C # 3.0 brings to us.

Now, we want to let the Person class implement the interface specification.

The following is a code snippet:

Public int Compare (Person x, Person y) {/ / assume that the ID of person is of type int return x.ID-y.ID;}

Then our implementation might be like this:

The following is a code snippet:

Arr.Sort ((new Person () as IComparer) comp); is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

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