The application of reflection and extension methods in C #

Source: Internet
Author: User

Some time ago did a practiced hand small project, called Book_bar, used to sell books, using a three-tier architecture, that is, MODELS,IDAL,DAL,BLL and the Web, in the DAL layer in each class has a method is more commonly used, that is Rowtoclass, as the name implies, That is, the data in the DataTable is encapsulated into the Models. As a result, many similar methods were written in the Dal classes, which were then extracted directly into the DataTable and DataRow extension methods.

Here's the code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Reflection;namespacedal{/// <summary>    ///extension methods for DataTable and DataRow/// </summary>     Public Static classTableextensionmethod {/// <summary>        ///Features:///extended a method to the DataTable to transform the rows in the datatable into corresponding class objects and encapsulate them in the list collection;/// </summary>        /// <typeparam name= "T" >the type of class that needs to be transformed</typeparam>        /// <param name= "table" >the incoming DataTable object</param>        /// <returns>returns a list collection that encapsulates the corresponding class</returns>         Public StaticList<t> tabletoclass<t> ( ThisDataTable table) {Type type=typeof(T); Propertyinfo[] Proparr= Type. GetProperties ();//Get all Propertieslist<t> list =NewList<t>(); DataRowCollection rows=table.            Rows; intLen = rows[0]. Itemarray.length;//gets the number of columns in the first row, that is, the number of attributes of class             for(inti =0; I < rows. Count; i++) {T T=(T) activator.createinstance (type);  for(intj =0; J < Len; J + +)//Proparr.length is not used here because some models properties do not have corresponding columns in the datasheet{proparr[j].                SetValue (t, Rows[i][j]); } list.                ADD (t); T=default(T); }            returnlist; }        /// <summary>        ///Features:///the extension method of the DataRow;///ability to encapsulate DataRow objects into generic objects/// </summary>        /// <typeparam name= "T" >the class type that needs to be converted</typeparam>        /// <param name= "Row" >the line being converted</param>        /// <returns>a class object that encapsulates the row data</returns>         Public StaticT rowtoclass<t> ( ThisDataRow Row) {            //Type type = Assembly.Load (classfullname). GetType ();Type type =typeof(T); T T=(T) activator.createinstance (type); Propertyinfo[] Proparr=type.            GetProperties (); intLen =row.            Itemarray.length;  for(inti =0; i < Len; i++) {Proparr[i].            SetValue (t, Row[i]); }            returnT; }        /// <summary>        ///Features:///the extension method of DataRowCollection;///ability to encapsulate datarowcollection objects into a generic list collection/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "Rows" ></param>        /// <returns></returns>         Public StaticList<t> rowtoclass<t> ( ThisDataRow Row, datarow[] rowarr) {Type type=typeof(T); Propertyinfo[] Proparr=type.            GetProperties (); intLen = rowarr[0]. Itemarray.length;//gets the number of columns in the first row of the data table, that is, the number of attributeslist<t> list =NewList<t>();  for(inti =0; i < rowarr.length; i++) {T T=(T) activator.createinstance (type);  for(intj =0; J < Len; J + +) {Proparr[j].                SetValue (t, Rowarr[i][j]); } list.                ADD (t); T=default(T); }            returnlist; }    }}

The above uses a generic, reflection, extension method.

There was a little bit of a problem with this line of code before:

Proparr[i]. SetValue (t, Row[i]);

A type conversion exception has been reported, after the breakpoint debugging is found because the arrangement of the attributes in the Models and the order of the columns of the data table is not the same, the reference data table in the order of the fields are modified, and one point is that when the Loop property is assigned, I choose the number of columns in the datasheet, not the number of attributes, (That is, the yellow part of the code).

The application of reflection and extension methods in C #

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.