CompareTo对象参数的变化
class program
{
static void Main(string[] args)
{
//One method
List<Customer> customers = new List<Customer>();
customers.Add(new Customer("HAHA"));
customers.Add(new Customer("MOMO"));
customers.Add(new Customer("GAGA"));
customers.Sort(Customer.Compare);
}
}
class Customer
{
public string CustomerName
{
get
{
return customerName;
}
set
{
customerName = value;
}
}
public Customer(string customerName)
{
this.customerName = customerName;
}
public static int Compare(Customer x, Customer y)
{
return x.CustomerName.CompareTo(y.CustomerName);
}
}
想知道,怎么通过Customer的两个对象参数对List进行排序的?
Compare方法中的参数变化如下:
HAHA MOMO
HAHA GAGA
MOMO HAHA
GAGA HAHA
HAHA HAHA
HAHA MOMO
HAHA HAHA
为什么会这样变化呢? 帮忙解释下好吗? 谢谢~! --------------------编程问答-------------------- 在线等待哦~! --------------------编程问答-------------------- 不明白你的意思
HAHA MOMO
HAHA GAGA
MOMO HAHA
GAGA HAHA
HAHA HAHA
HAHA MOMO
HAHA HAHA
这是什么 --------------------编程问答-------------------- 就是 x.CustomerName y.CustomerName
不知道 为什么是上面的结果 --------------------编程问答-------------------- 你这个程序里都没有Console.WriteLine --------------------编程问答--------------------
customers.Sort(
delegate(Customer x, Customer y)
{
Console.WriteLine("{0} vs {1}", x.CustomerName, y.CustomerName);
return x.CustomerName.CompareTo(y.CustomerName);
}
);
加个输出看看吧,我就是不明白这样的结果。
HAHA vs MOMO
HAHA vs GAGA
MOMO vs HAHA
GAGA vs HAHA
HAHA vs HAHA
HAHA vs MOMO
HAHA vs HAHA --------------------编程问答-------------------- sort是快速排序,它里面要反复比较。我看了sort的源码就是这个结果。你可以看下
补充:.NET技术 , C#