It makes you feel the encapsulated extension method is broken.

Source: Internet
Author: User

The extended method is derived from List <T>Where, Order, GroupByAnd other methods, smart sensing prompts that these methods are extension methods, so MSDNSummary:Custom Extension Method (convert string to Int, Code copy)

Namespace MyCommon


Public static class EString


Public static int ToInt (this string t)


Int id;

Int. TryParse (t, out id); // The id returned when the conversion fails.

Return id;




Required, Extension Method: 1, Must be static class and static method (and must be public)
, The parameter must use thisPrefix

At first glance, the extension method obviously violates the encapsulation principle and sets the method to public.For external calls, this is a very illegal encapsulation principle, but there is no way here, if it is changed to privateExternal instances cannot be accessed, but Microsoft told us that although the syntax of the instance method is used to call the extension method, the IL generated by the compilerIn the intermediate language, the code is converted into a call to a static method. In theory, the encapsulation principle is not really illegal, but this interpretation is somewhat far-fetched.

However, we found that the static class name is EString.It seems useless and can be changed at will. Indeed, all we need here is the namespace and method name, while the MethodThe first parameter determines the type of extension that the extension method is used.For example, the preceding example is this string t.The type of the first parameter is string., Is the stringExtension Method

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