日期:2014-05-17  浏览次数:21069 次

list泛型和类数组的问题
资料说泛型的出现是为了不用装箱和拆箱,但我定义一个类的数组也不用装箱和拆箱啊
请问以下代码的custormerList和custormerArr有什么区别.

C# code

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            List<Customer> custormerList = new List<Customer>();
            custormerList.Add(new Customer { CustomerID = 1, CustomerName = "张三" });
            custormerList.Add(new Customer { CustomerID = 2, CustomerName = "李四" });

            Customer c1 = new Customer { CustomerID = 1, CustomerName = "张三" };
            Customer c2 = new Customer { CustomerID = 1, CustomerName = "张四" };
            Customer[] custormerArr = new Customer[] { c1, c2 };

        }
    }
    public class Customer
    {
        public int CustomerID { get; set; }
        public string CustomerName { get; set; }
    }

}



------解决方案--------------------
我再举一个例子,比如在C# 1.0中,我们想实现一个比较器,我们这样定义基类:
class Comparer
{
//当a>b,返回>0的数,相等返回0,b>a返回<0的数
public virtual int CompareTo(object a, object b) { }
}
我们从它继承,比如我们定义一个比较日期的,我们可能希望这么写:
class DateTimeComparer : Comparer
{
public override int CompareTo(DateTime a, DateTime b) { }
}
但是很抱歉,这么写是不能编译的。我们只能写
class DateTimeComparer : Comparer
{
public override int CompareTo(object a, object b) { }
}
这样根本体现不了它是一个专门为DateTime比较而设计的类,有没有办法能实现呢?只能用泛型。