Main里加 Student[] _Value = new Student[5];
_Value[0] = new Student("A", 100, 100);
_Value[1] = new Student("B", 10, 20);
_Value[2] = new Student("C", 20, 50);
_Value[3] = new Student("D", 30, 60);
_Value[4] = new Student("E", 40, 77);
Array.Sort(_Value,_Value[0]);
具体类
public class Student : IComparer
{
private string m_Name = "";
private int m_Chinese = 0;
private int m_Maths = 0; public string Name { get{return m_Name;}set{m_Name=value;}}
public int Chinese { get { return m_Chinese; } set { m_Chinese = value; } }
public int Maths { get { return m_Maths; } set { m_Maths = value; } }
public int Sum { get { return m_Maths+m_Chinese; } } public Student(string p_Name, int p_Chinese, int p_Maths)
{
m_Name = p_Name;
m_Chinese = p_Chinese;
m_Maths = p_Maths;
} int IComparer.Compare(Object x, Object y)
{
Student _ValueX = (Student)x;
Student _ValueY = (Student)y; if (_ValueX.Sum == _ValueY.Sum) return 0; if (_ValueX.Sum > _ValueY.Sum) return 1;
return -1;
}
}
_Value[0] = new Student("A", 100, 100);
_Value[1] = new Student("B", 10, 20);
_Value[2] = new Student("C", 20, 50);
_Value[3] = new Student("D", 30, 60);
_Value[4] = new Student("E", 40, 77);
Array.Sort(_Value,_Value[0]);
具体类
public class Student : IComparer
{
private string m_Name = "";
private int m_Chinese = 0;
private int m_Maths = 0; public string Name { get{return m_Name;}set{m_Name=value;}}
public int Chinese { get { return m_Chinese; } set { m_Chinese = value; } }
public int Maths { get { return m_Maths; } set { m_Maths = value; } }
public int Sum { get { return m_Maths+m_Chinese; } } public Student(string p_Name, int p_Chinese, int p_Maths)
{
m_Name = p_Name;
m_Chinese = p_Chinese;
m_Maths = p_Maths;
} int IComparer.Compare(Object x, Object y)
{
Student _ValueX = (Student)x;
Student _ValueY = (Student)y; if (_ValueX.Sum == _ValueY.Sum) return 0; if (_ValueX.Sum > _ValueY.Sum) return 1;
return -1;
}
}
//class
public class Student
{
string name; public string Name
{
get { return name; }
set { name = value; }
}
float chinese; public float Chinese
{
get { return chinese; }
set { chinese = value; }
}
float math; public float Math
{
get { return math; }
set { math = value; }
}
public float Sum(float ch, float ma)
{
return ch + ma;
}
}
//main
static void Main(string[] args)
{
Student stu1 = new Student();
stu1.Name = "name one";
stu1.Chinese = 100;
stu1.Math = 100;
Console.Write("name chinese math sum");
Student stu2 = new Student();
stu2.Name = "name two";
stu2.Chinese = 200;
stu2.Math = 200;
Student stu3 = new Student();
stu3.Name = "name three";
stu3.Chinese = 300;
stu3.Math = 300;
Console.WriteLine();
Console.WriteLine(stu1.Name+" "+stu1.Chinese+" "+stu1.Math+" "+stu1.Sum(stu1.Chinese,stu1.Math));
Console.WriteLine(stu2.Name + " " + stu2.Chinese + " " + stu2.Math + " " + stu2.Sum(stu2.Chinese, stu2.Math));
Console.WriteLine(stu3.Name + " " + stu3.Chinese + " " + stu3.Math + " " + stu3.Sum(stu3.Chinese, stu3.Math));
}
实现IComparer 接口排序,顶!