你的位置:首页 > ASP.net教程

[ASP.net教程]C#的类,构造函数以及Array阵列的数据填充与绑定


今天学习,如标题。

创建一个类,字段属性构造函数:



Source code:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Insus.NET.Models{ public class Customer  {    public int CustomerID { get; set; }    public string CustomerName { get; set; }    public string PID { get; set; }    public Customer()    {    }    public Customer(int customerId, string customerName, string pID)    {      CustomerID = customerId;      CustomerName = customerName;      PID = pID;    }   }}

View Code


接下来,我们需要准备Array数据集,方法有好几路,每个元素的对象,由于构造函有重载,因此写法也不一样:
方法一:



public Customer[] ArrayCustoners()    {      Customer c1 = new Customer();      c1.CustomerID = 9;      c1.CustomerName = "张三";      c1.PID = "123456789012";      Customer c2 = new Customer(10, "李四", "321245677812");      Customer c3 = new Customer() { CustomerID = 30, CustomerName = "吴广", PID = "213445678912" };      return new Customer[]      {        c1,c2,c3      };    }

Source Code

 

方法二:

 

 public Customer[] ArrayCustoners1 = {      new Customer(9,"张三", "123456789012"),      new Customer(10,"李四","321245677812"),      new Customer() { CustomerID = 30, CustomerName = "吴广", PID = "213445678912" }    };

Source Code

 

方法三:

 

public Customer[] ArrayCustoners2()    {      Customer c1 = new Customer();      c1.CustomerID = 9;      c1.CustomerName = "张三";      c1.PID = "123456789012";      Customer[] array = new Customer[3];      array[0] = c1;      array[1] = new Customer(10, "李四", "321245677812");      array[2] = new Customer() { CustomerID = 30, CustomerName = "吴广", PID = "213445678912" };      return array;    }

Source Code

 

方法四:

 

public Customer[] ArrayCustoners3()    {      Customer c1 = new Customer();      c1.CustomerID = 9;      c1.CustomerName = "张三";      c1.PID = "123456789012";      return new Customer[]      {        c1,        new Customer(10, "李四", "321245677812"),        new Customer() { CustomerID = 30, CustomerName = "吴广", PID = "213445678912" }      };    }

Source Code


也许还有其它写法,Insus.NET暂列出四种,根据上面来看,第二种是最简单的写法,不过在创建类别以及其构造方法,需要重载带参数的构造函数。