Whatever you want ~ I also want to create a set traversal tool (My foreach, the power of delegation)

Source: Internet
Author: User

I feel that Microsoft has the most outstanding application of encapsulation among the three object-oriented principles. It will encapsulate some complex algorithms, structures, and functional code, so that programmers can be very comfortable with using them, for example, the foreach In the keyword and the Foreach in the labmda expression. Today I also wrote a set traversal tool.

TIPS: If your set is List, you can use multiple N methods in it. Today's traversal function is implemented using the GetEnumerator () method in List, it actually returns an Enumerator result body. The structure of this Enumerator is as follows:

  Enumerator : IEnumerator<T>                         T Current {             [TargetedPatchingOptOut(                                                  

It has an attribute Current and a method MoveNext, which is the prerequisite for implementing the traversal. The Current attribute outputs the Current value, and MoveNext points the set to the next element, the return value is of the bool type. "true" indicates that the next element exists. "false" indicates that the set has been traversed.

With the above knowledge, we can work with the delegated Action <T> to design our own foreach method.

                                                       ForeachZzl<T>(IList<T> list, Action<T> e =

Calling this method is also very simple. Because the delegate is used, as long as you have an input parameter T, you can apply it to all method bodies.

            List<> enums =  List<> { , , , , =>

How about it? Is it a bit like Microsoft's Foreach lambda? haha, in fact, we add an extension method and it turns into lambda. Look at the code.

               ForeachZzl<T>( IList<T> list, Action<T> e =

Are you familiar with the following calls?

            enums.ForeachZzl(i =>

Through this article, we can fully appreciate the power of delegation.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.