加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

泛型与序列化

发布时间:2020-12-17 02:39:41 所属栏目:安全 来源:网络整理
导读:private IList CustomersM GetAllCustomers() { ??? IList CustomersM customer = new List CustomersM (); ??? using ( SqlConnection connection = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "cc_2005" ].ConnectionString)) ??? { ?

private IList<CustomersM> GetAllCustomers()

{

??? IList<CustomersM> customer = new List<CustomersM>();

??? using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["cc_2005"].ConnectionString))

??? {

??????? connection.Open();

??????? SqlCommand command = new SqlCommand("SELECT? [CompanyName],[ContactName],[ContactTitle],[Address],[City] FROM [Customers]",connection);

??????? SqlDataReader sdr=command.ExecuteReader(CommandBehavior.CloseConnection);

??????? while (sdr.Read())

??????? {

??????????? //实体类中没有初始化属性的构造函数

??????????? /*CustomersM m = new CustomersM();

??????????? m.CompanyName = sdr[0].ToString();

??????????? m.ContactName = sdr[1].ToString();

??????????? m.ContactTitle = sdr[2].ToString();

??????????? m.Address = sdr[3].ToString();

??????????? m.City = sdr[4].ToString();

???????????? *

???????????? */

??????????? //实体类中有初始化属性的构造函数

??????????? CustomersM m = new CustomersM(sdr[0].ToString(),sdr[1].ToString(),sdr[2].ToString(),sdr[3].ToString(),sdr[4].ToString());

??????????? customer.Add(m);

??????? }

??????? return customer;

??? }

}

?

3.这样GetAllCustomers就可以绑定到GridView,DropDownList等控件上了。

注意:IList是不能序列化的,因此当需要序列化的时候(如:webservice,由于webservice中传递的对象都是可以序列化的)必须使用System.Collections.ObjectModel.Collection< >

?

代码如下:

private System.Collections.ObjectModel.Collection<CustomersM> GetCustomers()

{

??? System.Collections.ObjectModel.Collection<CustomersM> customer = new System.Collections.ObjectModel.Collection<CustomersM>();

??? using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["cc_2005"].ConnectionString))

??? {

??????? connection.Open();

??????? SqlCommand command = new SqlCommand("SELECT? [CompanyName],connection);

??????? SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);

??????? while (sdr.Read())

??????? {

??????????? CustomersM m = new CustomersM(sdr[0].ToString(),sdr[4].ToString());

??????????? customer.Add(m);

??????? }

??????? return customer;

??? }

}

?

webservice中如果把上面两个调用数据库的方法搬过去(好多命名空间要添加),使用IList<>类型的就会报错,“IList不能序列化接口”,而使用Collection<>的就可以正常使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读