C # Features-extension methods

Source: Internet
Author: User

public static class Propertyextension{public        static Object Getvaluebyname (This object self, string propertyname) 
   {            if (self = = null)            {                return self;            }            Type t = self. GetType ();            PropertyInfo p = t.getproperty (propertyname);            Return p.getvalue (self, null);}        }

Extension methods:

1 The class where the method resides must be static

The 2 method must also be static

The first parameter of the 3 method must be the type you want to extend, for example if you want to extend a method to int, then the first argument must be int.

4 A This keyword is also required before the first parameter.

String str = "ABC";
object len = Str. Getvaluebyname ("Length");

Attention:

Many people see the expansion method may be in the eyes of the golden, later in the design of the time regardless of 3,721, anyway, can be expanded. Others will arbitrarily extend the class, using some of the previous methods as "Helper" instead of extension methods, note that the extension method is "polluting", so I think in the expansion of the time to think about it is not worth expanding.

Do not extend the higher-level classes at the time of expansion, as I am facing an object extension I think is undesirable, object is the base class of all classes, once extended, all classes are "contaminated".

C # Features-extension methods

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.