class Program
{
static void Main(string[] args)
{
Student stu1 = new Student("tom", 3, "男");
Student stu2 = new Student("jack", 12, "男");
Student stu3 = new Student("rose", 34, "男");
Student[] stus = { stu1, stu2, stu3 };
//IComparable ic = new StudentCompare();
//Array.Sort(stus, ic);
Array.Sort(stus, new StudentCompare());
//为什么能new StudentCompare()就能调用其方法???
Array.Sort(stus, new StudentCompare().Compare()); //报错???
//for (int i = 0; i < stus.Length; i++)
//{
// Console.WriteLine(stus[i].ShouMe());
//}
Console.WriteLine(new Student().ShouMe());
Console.WriteLine(new StudentCompare().Compare());
//报错???
}
}
class StudentCompare : IComparer
{
public int Compare(object x, object y)
{
int i = 0;
if ((x is Student) && (y is Student))
{
Student s1 = x as Student;
Student s2 = y as Student;
i = s1.Name.CompareTo(s2.Name);
}
return i;
}
}
public class Student
{
public Student()
{
}
public Student(string name, int age, string gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
private string _gender;
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
public string ShouMe()
{
Console.WriteLine("sdfgh");
return $"姓名:{Name } 年龄:{Age } 性别:{Gender}";
}
}
我前面已经回复过你了,接口参数只需要接受IComparer的派生对象即可,具体使用是在Array.Sort方法内部会调用这个对象的Compair方法完成对数组的排序
怎么调用的?这只是一个派生类的实例啊!虽然转成了接口类型
@功夫之我玩: 内部实现是用的快排,但不管怎么实现总要有地方告知怎么比较两个元素的大小吧?这个地方就是通过这个接口参数告知的。
比如
bool GreaterThan(Student a,Student b,IComparer comparer)
{
//...忽略参数校验等逻辑
return comparer(a,b)>=0;
}
实际中建议使用泛型接口。
Array.Sort(stus, new StudentCompare().Compare()); //报错??? 因为你定义的Compare是有参数的.
你带上参数按照定义的来看看报错不.不要在语法上纠结语法是对是错.因为语法不会错.错了一定是你不按照语法来
就跟1+1=2不用想一样.你只需要知道1+1等于2就行了.
他在里面怎么调用的管你什么事?想知道他怎么调用的就去看他的代码.