泛型的用处还有优点什么的我就不说,因为我也没有完全理解,只是知道泛型是类型安全的免除了拆箱装箱的操作,性能会好点;还有就是泛型其实就是将类参数化(一家之言)

下面就介绍一下petshop中用到的泛型吧!

微软主要是在业务逻辑层进行操作数据库的时候用到了泛型,将实体类传过去进行操作而不是对实体类的每个属性单独操作。

下面就贴一段代码(语文水平太差,写着太费劲)

1.实体类的代码就不贴了吧(就是一些getter,setter)(微软推荐:实体类要可以序列化)

2.只是一般的测试也没有分层,把逻辑层放在表现层中间了啊

privateIList<CustomersM> GetAllCustomers()

{

    IList<CustomersM> customer = newList<CustomersM>();

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

    {

        connection.Open();

        SqlCommand command = newSqlCommand("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 = newCustomersM(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 = newSqlConnection(ConfigurationManager.ConnectionStrings["cc_2005"].ConnectionString))

    {

        connection.Open();

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

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

        while (sdr.Read())

        {

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

            customer.Add(m);

        }

        return customer;

    }

}

友情提示:

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

posted on 2008-01-17 09:30  lunar  阅读(182)  评论(0编辑  收藏  举报