Share. NET system development process accumulated in the extension method

Source: Internet
Author: User

The extension method attribute provided by. NET 3.5 can extend its functionality without modifying the original type code. Most of these extension methods that are shared below are from code project or StackOverflow. NET also has a Web site (extensionmethod) dedicated to extending methods.

It covers the extension of type conversion, string processing, time conversion, collection operation and many other aspects.

1 Tolerantcast Anonymous type conversion

This requirement comes from the use of BackgroundWorker in the interface, in order to pass multiple parameters to DoWork, and do not want to define a type to complete, so I will use the Tolerantcast method. Refer to the following code:

//create anonymous type  var parm = new  {bucket = bucket, Auxiliaryaccischeck = chbauxiliaryacc.checked, Allaccountischeck = chballaccount.checked}; Backgroundworker.runworkerasync (Parm); private  void  backgroundworker_dowork (object  sender, DoWorkEventArgs e) {//parse convert anonymous type  var parm = e.argument.tolerantcast (new  {Bucket = new  relationpredicatebucket (), Auxiliaryaccischeck = false , Allaccountischeck = false }); 

2 ForEach Collection Operations

The definition of this method is simple but practical, and it is used in the following ways:

 as ienumerable<button>; Buttons. ForEach (b = B.click ());

The source code definition for an extension method is only one line, as follows:

 Public Static void Foreach<t> ( this ienumerable<t> @enum, action<t> mapfunction) {    foreach   in @enum) mapfunction (item);}

This method is often used when I want to perform the same operation on each element of a collection.

3 Capitalize string first letter capitalization

directly to the string operation, the first letter of the string is changed to uppercase, the source code reference is as follows:

public  static        String  capitalize (this  string  word) { if  (Word.      Length <= 1) return  word; return  word[0]. ToString (). ToUpper () + Word. Substring (1);} 

4 todatatable strongly typed object collection into a DataTable

Development often encounters a code that transforms list<entity> into a DataTable, or instead transforms a DataTable into a list<entity>,stackoverflow with a lot of this requirement, Refer to the following program code:

  Public StaticDataTable todatatable<t> ( ThisIenumerable<t> varlist) {DataTable Dtreturn =NewDataTable ();//column namespropertyinfo[] Oprops =NULL;if(Varlist = =NULL)returnDtreturn;foreach(T RecinchVarlist) {//Use reflection-get property names, to-create TABLE, only first time, others'll follow                if(Oprops = =NULL{Oprops = ((Type) rec.) GetType ()). GetProperties ();foreach(PropertyInfo PiinchOprops) {Type coltype = pi. PropertyType;if((Coltype.isgenerictype) && (coltype.getgenerictypedefinition () = =typeof(nullable<>)))                        {Coltype = coltype.getgenericarguments () [0]; } DTRETURN.COLUMNS.ADD (NewDataColumn (pi.                    Name, Coltype)); }} DataRow Dr = Dtreturn.newrow ();foreach(PropertyInfo PiinchOprops) {Dr[pi. Name] = pi. GetValue (REC,NULL) ==NULL? DBNull.Value:pi. GetValue (REC,NULL);            } dtReturn.Rows.Add (DR); }returnDtreturn; }

5 Setallvalues assigning values to each element in the array

The implementation assigns the same value to each element in the array.

public  static  t[] Setallvalues<t > (this  t[] array, T value ) {for  ( Span class= "KWRD" >int  i = 0; I < array. Length;     i++) {Array[i] = value ; } return  array;} 

6 ToXml serialized object as XML format

You can serialize an object into an XML-formatted string that holds the state of the object.

 Public Static string Toxml<t> (thiswherenew() {        string retVal;        using New MemoryStream ())        {              new XmlSerializer (typeof (T));               Xs. Serialize (MS, O);               Ms. Flush ();               Ms. Position = 0;               New StreamReader (MS);               RetVal = Sr. ReadToEnd ();        }        return RetVal;}

7 between value range comparison

You can determine whether a value falls within the interval range value.

 Public Static BOOL Between<t> (thiswhere t:icomparable<t>{      return me.) CompareTo (lower) >= 0 && me. CompareTo (upper) < 0;}

For operations like this, the following method is to take the maximum value of 2 values.

 Public Static where t:icomparable{     return value1.compareto (value2) > 0? Value1:value2;}
8 StartDate duedate Start value or end value

Time comparisons are often used in business systems, If the system is used DateTime.Now variable and datetime.today to compare, the former is always greater than the latter, for this need to do a simple conversion, as needed to convert the value to start or end value, that is, 0 points 0 minutes 0 seconds, or 23:59 59 seconds.

 Public Static DateTime convertostartdate ( this datetime datetime) {     returnnew datetime ( Datetime.year, DateTime.Month, datetime.day, 0, 0, 0);}  Public Static DateTime convertoduedate ( this datetime datetime) {      returnnew datetime ( Datetime.year, DateTime.Month, DateTime.Day, 23, 59, 59);}
9 first day or the last day of the month
 Public Static DateTime First ( this datetime current) {       datetime first = current. AddDays (1-current. Day);       return first;}
 Public Static DateTime Last ( this datetime current) {      int daysinmonth = datetime.daysinmonth (current. Year, current. Month);       DateTime last = current. First (). AddDays (daysInMonth-1);       return last;}


Percent percent Value

Calculates the previous value as a percentage of the last value, often used in statistical terms.

public  static   Decimal  percentof (this  double  position,     int  total) {decimal  result = 0; if  (Position > 0 && Total > 0) result= (decimal ) (decimal
    ) position/(decimal ) total * 100); return  result;} 

Extension method source code download: Http://files.cnblogs.com/files/JamesLi2015/ExtensionMethod.zip

Share. NET system development process accumulated in the extension method

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.