PDA

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



esafb52
چهارشنبه 16 دی 1394, 08:48 صبح
با سلام
فواید اینترفیس ها در برنامه نویسی شی گرا بر کسی مخفی نیست !!! امروز یکی از اینترفیس های خود دات نت (IComparer) رو با هم پیاده سازی میکنم !!!یک سناریو رو در نظر بگیرین که ما یک کلاس ساده داشته باشیم و بخواهیم اون رو مرتب کنیم مثلا براساس معدل


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


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


}

حالا اگر مثلا در یک نوع جنریک بخواهیم از این استفاده کنیم و بخواهیم مثلا از متد sort استفاده کنیم چه اتفاقی می افته ؟؟؟ بله اتفاقی نمی افته
فقط کامپایلر یک خطا صادر میکنه و میگه من نمیدونم چطور مرتبش کنم چون بهش چیزی راجب این نگفتیم حالا این اینترفیس رو به این صورت پیاده سازی یا ایمپلیمنت میکنیم



public class comstude : IComparer<student>
{


public int Compare(student x, student y)
{
return x.avrage.CompareTo(y.avrage);
}


}


public class student
{
public string name;
public double avrage;
public student(string name1, double av)
{
this.name = name1;
this.avrage = av;
}




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


templist.Add(new student("esa", 10));
templist.Add(new student("reza", 20));
templist.Add(new student("reza1", 17.50));
templist.Add(new student("reza2", 16));
templist.Add(new student("reza3", 19));
templist.Add(new student("reza4", 7));
return templist;
}




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


}

و در نهایت به این صورت استفاده میکنیم !!!


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


List<student> list = student.getstudentlist();
list.Sort(new comstude());


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

ساده بود نه !!!