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

Example Analysis of delegation and Interface in .NET

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

Share

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

This article mainly introduces the example analysis of delegation and interface in .NET, which is very detailed and has a certain reference value. Interested friends must read it!

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:

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.

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. :)

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.

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:

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.

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:

Arr.Sort ((new Person () as IComparer) comp)

I can't give you any more examples. I admit I lied to you. There is an essential difference between these seemingly feasible implementations!

First of all, let's look at * delegate examples: in Calculate, our delegate is allowed to use the two variables within the method, amemb, thus changing the result of the whole method. Delegating is passive throughout the process because it does not know when it will be triggered. The above example is very simple, so that you do not feel this way, and as mentioned earlier, when the delegate is triggered during the execution of the method, we can do something else, such as doing a logging or something. At this time, the interface has the ability to do logging without destroying the running structure of the method itself? Obviously, the class that implements the interface can only override the method once.

Passerby A: then I'll call the original method again in the implementation of the interface. Won't I just add the logging function before or after the method?

Snake: how can you kill a chicken with a cow knife? Not to mention the feasibility of the original method, even if it is feasible, not to mention, what if there are multiple stages in the implementation of this method, and each stage has to be logged? Delegate can go deep into the method, and the method controls the place where it is placed, so that the delegate can play a key role. At this time, the cow knife as the interface boss can not clean the meat on the chicken bone.

Secondly, it talks about the advantages of interface. We can see that the delegate can go deep into the method, that is to say, the delegate's concern group is the method, while the interface's concern group is the class. The interface requires the class to implement the same signed method or property in order to call a variable method in the program. Since it is because of the class, then its method must be immutable. Every class that implements the interface, even if the function is almost complete, must be written again, but the class has a large territory and a lot of ink. Although the method that can be called through ICal in the Add class is only a Calculate (), but in the Calculate class is always the people of the Add class, so the Calculate method can call all the callable resources in the Add class. And if it is the Sub class, its people Caculate can call different resources from the Add class, after all, it is the same Calculate, different nationalities, different culture and way of life, .

However, the ability of the interface is beyond the reach of the delegate. It can only be hidden by the method, and there is a blue sky outside the method, but there is nothing it can do. If we compare the class to a country and the method to a person, then isn't entrusting the thinking of the way of processing hidden in the brain of the people's Congress? The thinking of different people can change. When rural people see the tall buildings in the city, they can't help sighing, but after the rural people have their living habits in the city, he has long been used to it.

The above is all the content of the article "sample Analysis of delegation and Interface in .NET". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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