What is the return value? --Generic practice

Source: Internet
Author: User
Tags date1

for a preliminary understanding of generics, see http://blog.csdn.net/lifen0908/article/details/43450921. This blog is mainly about the use of generics in the computer room.

First, if it is a return value entity:

I use the window that queries the student's basic information to illustrate the case when our return value is an entity:

The first is the D layer:

<span style= "font-family:kaiti_gb2312;" > Dim sql As String ' defines a string variable SQL is used to hold the SQL statement to execute Dim table as DataTable ' Define table variable tables to store execution results and return Dim paras A S SqlParameter () = {New SqlParameter ("@cardno", Studinfo.cardno)} sql = "select * from student_info where Cardno = @cardno "table = Sqlhelper.SqlHelper.ExecSelect (SQL, CommandType.Text, paras) Dim studententity as New enti Ty. Studentinfo If table. Rows.Count <> 0 Then Studententity.cash = table. Rows (0). Item ("cash") Studententity.department = table. Rows (0). Item ("department") Studententity.grade = table. Rows (0). Item ("grade") Studententity.sex = table. Rows (0). Item ("sex") Studententity.studentno = table. Rows (0). Item ("Studentno") Studententity.txtclass = table. Rows (0). Item ("class") Studententity.cash = table. Rows (0). Item ("cash") Studententity.studentname = table. Rows (0). Item ("Studentname") studententity.department = table. Rows (0). Item ("department") Studententity.grade = table. Rows (0). Item ("grade") Studententity.sex = table. Rows (0). Item ("sex") studententity.status = table. Rows (0). Item ("status") Studententity.ischeck = table. Rows (0). Item ("Ischeck") End if</span>
<span style= "font-family:kaiti_gb2312;" >return studententity</span>
<span style= "font-family:kaiti_gb2312;" >  </span>

As you can see, if our return value is an entity, in the D layer, we first need to assign the table already queried to the DataTable, which is the table defined here, and then assign each field in the table to the entity, which is the studententity written here.

Look at the U-layer:

<span style = "font-family:kaiti_gb2312;" >dim strResult2 as Entity.studentinfo strResult2 = Chastu.querycardno (studinfo) If isnothing (STRRESULT2) Then MsgBox ("User does not exist") Txtcardno. Text = "" Txtcardno. Select () Txtcardno. Focus () Else Txtstudentno. Text = Strresult2.studentno Txtclass. Text = Strresult2.txtclass Txtcash. Text = Strresult2.cash txtname. Text = Strresult2.studentname txtdepartment. Text = Strresult2.department Txtgrade. Text = Strresult2.grade Txtsex. Text = Strresult2.sex Txtstatus. Text = Strresult2.status Txtps. Text = Strresult2.ischeck End if</span> 

d layer query to the assignment to the entity, and then in the U layer, each entity is assigned to the text box on the form, and then completed the D-level query to the U-layer function, this is the transfer entity, the return value is also an entity. This is obviously a very troublesome thing to do.

second, if the return value is a DataTable

We use the computer room charge system in the basic data set form to illustrate, the basic data set the first step is to set the database of basic data set query results reflected on the form, we look at the code.

D-Tier Code:

<span style= "font-family:kaiti_gb2312;" > Dim sql As String        Dim table As DataTable        sql = "SELECT * from Basicdata_info"        table = Sqlhelper.sqlhelper . Execselectno (SQL, CommandType.Text)        Return table</span>
D-layer operation is to delete and change, so almost all are duplicated code.

The Code of the U-layer directly assigns the contents of the table to the text box, where the code is omitted.

As you can see, returning datetable is much simpler than returning an entity.

third, return to generics (MyList)1. Package Public Function--generic type

Generics are also a table that, through a function, a query parameter, gives the result of the query to a table.

First of all, generics and Sqlhelp, as well as a common function, need to be encapsulated, because in the D layer need to use it very frequently, so I create a class on the D layer, write down this function. Of course, his limit is that the entity's attribute name must correspond to the column name.

<span style= "font-family:kaiti_gb2312;" >imports System.Collections.Generic ' Add a generic namespace Imports system.reflection ' add reflection in order to use Propertyinfopublic Class Converthelper ' Convert a DataTable to a generic collection public Shared Function converttolist (of T as {New}) (ByVal DT as DataTable) as IList        (of T) ' Note: converttolist (Of T as {New}) Here is used to constrain T, there must be, otherwise new T will appear error when Dim myList as New List (Of T) ' defines the final returned set D Im Mytpye as type = GetType (T) ' Get the type name of the entity class Dim dr As DataRow ' define rowset Dim tempname As String = String.Empty ' definition A temporary variable for every dr in Dt. Rows ' traverse all data rows of the DataTable Dim MyT As New T Dim propertys () as PropertyInfo = Myt.gettype (). GetProperties () Dim PR as PropertyInfo for each PR in propertys tempname = pr. Name If (dt. Columns.contains (tempname)) then If (pr. CanWrite = False) then Continue for End If Dim value as Object = Dr (Tempname) If (value. ToString <> DBNull.Value.ToString ()) then PR.        SetValue (MyT, value, nothing) End If End If Next mylist.add (MyT) Next Return myList End functionend class</span>

already packaged generics have been written, and then look at how to use it .

2. Using public functions-generics(1) Form

The query to a table is all used to display in the control, here we take the amount of inquiry as an example.


(2) Entity code

First of all, because here is a start date, an end date, so at the entity level, I added two more entities than the fields in the database, that is, the following two, the other entities are not listed here.

<span style= "font-family:kaiti_gb2312;" > Public Property  redate1 As String        get            Return _date1        End Get        Set (value as String)            _date1 = Value        End Set End Property Public property    Redate2 as    String        Get            Return _date2        End get< C16/>set (value as String)            _date2 = value        end Set    End property</span>


(3) interface code

Then is the interface layer, in fact, the wording is not difficult, but the first time with a lot of mistakes.

<span style= "font-family:kaiti_gb2312;" > Function ichargequ (ByVal LDate as Entity.rechargeinfo) as List (of Entity.rechargeinfo) </span>

(4) D-Layer Code

<span style= "font-family:kaiti_gb2312;" >imports idalimports entityimports System.Data.SqlClientImports sqlhelper.sqlhelperpublic Class Sqlserverrechargeinfodal:implements irechargeinfo public Function ichargequ (LDate as Rechargeinfo) as List (of Recharg  Einfo) Implements irechargeinfo.ichargequ Dim sql As String ' Define string variable SQL to hold SQL statement to execute Dim table as DataTable ' Table variable ' is used to store the result of execution and returns the Dim MyList as List (of entity.rechargeinfo) sql = "SELECT * FROM Recharge_info wher E redate >= @redate1 and redate<= @redate2 "Dim paras as SqlParameter () = {New SqlParameter (" @redate1 ", Ldat e.redate1), New SqlParameter ("@redate2", ldate.redate2)} table = Sqlhelper.sq Lhelper.execselect (SQL, CommandType.Text, paras) If table. Rows.Count > 0 Then mylist = converthelper.converttolist (of entity.rechargeinfo) (table) Return my List Else Return nothing End If EnD function</span> 

(5) U-Layer Code

The code for the factory and B layers is not here, so let's look at the code for the U-layer:

<span style= "font-family:kaiti_gb2312;"  > Private Sub button1_click (sender as Object, e as EventArgs) Handles Button1.Click Dim date1 As Date Dim Date2 as Date date1 = Datetimepicker1.value date2 = datetimepicker2.value If DateDiff ("n", CDate (Dat            E1), CDate (date2)) < 0 then MsgBox ("date conflicts, re-modify", vbOKOnly + vbexclamation, "Modified date") Exit Sub Datetimepicker1.focus () End If Dim EDate As New Entity.rechargeinfo Dim bdate As New BLL. CHARGEQUBLL Dim Ldater as New List (of entity.rechargeinfo) edate.redate1 = date1 Edate.redate2 = Date 2 Ldater = bdate.chargequ (EDate) If isnothing (ldater) = False then Datagridview1.datasource = LDa            ter DataGridView1.Columns.Remove ("redate1") DataGridView1.Columns.Remove ("Redate2") Else Date1 = "" Date2 = "" End If end sub</span>

because of the DataGridView control, all fields in the entity layer will be his column name Datagridview.columns.remove ("Redate1") to remove him.

In this way, all the data you have queried is displayed on the control DataGridView. That's the very important DataGridView. Datasource=ldater.

(6) Partial display of the query

But what if we don't show all the content and just need one of his data? The syntax is very simple, here is the list of the generic values assigned to the text box, as follows: Txttype. Text = mylist (0). Type txtname. Text = mylist (0). studentname


Four, sentiment

What is first difficult after easy, a full grasp of it, into their own things, into their own understanding, it is not so difficult.

Refactoring, refueling ~~~~~~~~~~



What is the return value? --Generic practice

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.