日期:2014-05-17  浏览次数:20825 次

简单的学生信息排序问题,(接口)
/// <summary>
  /// 年龄升序
  /// </summary>
  public class AgeSort : IComparer<Student>
  {
  public int Compare(Student x, Student y)
  {
  return x.StdBorn.CompareTo(y.StdBorn);
  }
  }
  /// <summary>
  /// 年龄倒序
  /// </summary>
  public class AgeDescSort : IComparer<Student>
  {
  public int Compare(Student x, Student y)
  {
  return y.StdBorn.CompareTo(x.StdBorn);
  }
  }
  /// <summary>
  /// 姓名升序
  /// </summary>
  public class NameSort:IComparer<Student>
  {

  public int Compare(Student x, Student y)
  {
  return x.Name.CompareTo(y.Name);
  }
  }
  /// <summary>
  /// 工厂类
  /// </summary>
  public class Factory
  {
  public static IComparer<Student> StuSort(string sortType)
  {
  return Assembly.GetAssembly(typeof(Factory)).CreateInstance("ConsoleApplication2."+sortType) as IComparer<Student>;
  }
  }
   
  /// <summary>
  /// 学生类
  /// </summary>
  public class Student : IComparable<Student>
  {
  //学号
  public int stdId { get; set; }
  //姓名
  public string Name { get; set; }
  //座位号
  public int SeatNo { get; set; }
  //出生日期
  public DateTime StdBorn { get; set; }


  public int CompareTo(Student other)
  {
  return this.stdId.CompareTo(other.stdId);
  }
  }


  class Program
  {
  static void Main(string[] args)
  {

  List<Student> stuList = new List<Student>()
  {
  new Student{stdId=4,Name="b",SeatNo=2,StdBorn=new DateTime(1991,1,1)},
  new Student{stdId=3,Name="c",SeatNo=3,StdBorn=new DateTime(1993,1,1)},
  new Student{stdId=2,Name="d",SeatNo=4,StdBorn=new DateTime(1994,1,1)},
  new Student{stdId=1,Name="a",SeatNo=1,StdBorn=new DateTime(1992,1,1)},
   
  };

  stuList.Sort(Factory.StuSort("AgeSort"));

  for (int i = 0; i < stuList.Count; i++)
  {
  Console.WriteLine(stuList[i].stdId+"\t"+stuList[i].Name+"\t"+stuList[i].SeatNo+"\t"+stuList[i].StdBorn);
  }

  Console.WriteLine();
  stuList.Sort(Factory.StuSort("NameSort"));

  for (int i = 0; i < stuList.Count; i++)
  {
  Console.WriteLine(stuList[i].stdId + "\t" + stuList[i].Name + "\t" + stuList[i].SeatNo + "\t" + stuList[i].StdBorn);
  }
  }
  }


  以上是代码,stuList.Sort(Factory.StuSort("NameSort"));我调用工厂类的方法使却不走那个对象内部的方法,反而走Student类的方法,每次排序结束都是stdID顺序,很是苦恼,求好心朋友相助

------解决方案--------------------