泛型与序列化
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<>的就可以正常使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |