泛型与序列化

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], [ContactName], [ContactTitle], [Address], [City] FROM [Customers]", connection);

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

        while (sdr.Read())

        {

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

            customer.Add(m);

        }

        return customer;

    }

}

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值