PDA

View Full Version : آموزش: آموزش پیاده سازی اینترفیس IComparable



esafb52
چهارشنبه 16 دی 1394, 21:37 عصر
با سلام ضمن تشکر از استاد محمود افراد برای توضیح خوبشون در مورد آموزش قبلی در ادامه آموزش قبل این بار اینترفیس IComparable رو با هم پیاده سازی می کنیم
به فرض داستن این کلاس

public class student
{
public string name;
public double avrage;

public student()
{

}
public student(string name, double avg)
{
this.name = name;
this.avrage = avg;
}


public static List<student> Getstudentlist()
{
List<student> templist = new List<student>();

templist.Add(new student("esa", 10));
templist.Add(new student("alis", 20));
templist.Add(new student("jac", 17.50));
templist.Add(new student("jon", 16));
templist.Add(new student("toni", 19));
templist.Add(new student("hamfer", 20));
return templist;
}


}

ابتدا کلاسمون رو به این شکل باید پیاده سازی کنیم

public class student : IComparable<student>
{
public string name;
public double avrage;

public student()
{

}
public student(string name, double avg)
{
this.name = name;
this.avrage = avg;
}


public static List<student> Getstudentlist()
{
List<student> templist = new List<student>();

templist.Add(new student("esa", 10));
templist.Add(new student("alis", 20));
templist.Add(new student("jac", 17.50));
templist.Add(new student("jon", 16));
templist.Add(new student("toni", 19));
templist.Add(new student("hamfer", 20));
return templist;
}
//پیاده سازی متد این اینترفیس
public int CompareTo(student other)
{
if (this.avrage > other.avrage)
return -1;
if (this.avrage == other.avrage)
return 0;
return 1;

}

public override string ToString()
{
return string.Format("name is : {0}\t and average is\t {1}", name, avrage);
}



}

و به این شکل هم باید استفاده کنیم!!!

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

List<student> list = student.Getstudentlist();
// sort list
list.Sort();

foreach (student var in list)
{
Console.WriteLine(var);
}
Console.ReadKey();
}
}