资料说泛型的出现是为了不用装箱和拆箱,但我定义一个类的数组也不用装箱和拆箱啊
请问以下代码的custormerList和custormerArr有什么区别.
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; }
}}
请问以下代码的custormerList和custormerArr有什么区别.
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; }
}}
但我想知道泛型真正应用在哪里,能举下例子吗,,不要就传个类进去,就SHOW个类型出来这样,要实际应用
public void MyDelegate(int x, int y, string z); 这样的东西了。因为这个类型直接就可以表达为Action<int, int, string>。
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比较而设计的类,有没有办法能实现呢?只能用泛型。