程序是这样的class Person
{
public string Name;
public int Age; public Person(string name, int age)
{
Name = name;
Age = age;
}
}
public class PersonComparerName : IComparer
{
public static IComparer Default = new PersonComparerName(); public int Compare(object x, object y)
{
if (x is Person && y is Person)
{
return Comparer.Default.Compare(
((Person)x).Name, ((Person)y).Name);
}
else
{
throw new ArgumentException("one or both objects to compare are not person .");
}
}
} class Program
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add(new Person("Jim", 30));
list.Add(new Person("Bob", 25));
list.Add(new Person("Bert", 27));
list.Add(new Person("Ernie", 22)); Console.WriteLine("people sorted with comparer(by age):");
Console.WriteLine("People sorted with nondefault comparer(by name):");
list.Sort(PersonComparerName.Default);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("{0} {1}", (list[i] as Person).Name,
(list[i] as Person).Age);
}
}
}
想问的是 public static IComparer Default = new PersonComparerName();
这句的含义是什么?是不是一定要这样写的呢?
{
public string Name;
public int Age; public Person(string name, int age)
{
Name = name;
Age = age;
}
}
public class PersonComparerName : IComparer
{
public static IComparer Default = new PersonComparerName(); public int Compare(object x, object y)
{
if (x is Person && y is Person)
{
return Comparer.Default.Compare(
((Person)x).Name, ((Person)y).Name);
}
else
{
throw new ArgumentException("one or both objects to compare are not person .");
}
}
} class Program
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add(new Person("Jim", 30));
list.Add(new Person("Bob", 25));
list.Add(new Person("Bert", 27));
list.Add(new Person("Ernie", 22)); Console.WriteLine("people sorted with comparer(by age):");
Console.WriteLine("People sorted with nondefault comparer(by name):");
list.Sort(PersonComparerName.Default);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("{0} {1}", (list[i] as Person).Name,
(list[i] as Person).Age);
}
}
}
想问的是 public static IComparer Default = new PersonComparerName();
这句的含义是什么?是不是一定要这样写的呢?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货