System.IComparable
این interface شما رو موظف می کنه که یک متد به نام CompareTo به کلاستون اضافه کنید.
public int CompareTo(object obj)
{
....
}
با این متد میشه همیشه دو شی از اون کلاس رو با هم مقایسه کرد.
وجود چنین متدی برای انجام بسیاری از عملیات همچون sort کردن، کاملا حیاتی است.
اگر من کلاس خودم را این چنین تعریف کنم:
public class myClass : IComparable
{
...
public int CompareTo(object obj)
{
....
}
}
و بعد یک Collection از اون را بسازم:
ArrayList<myClass> myInstance = new ArrayList<myClass>();
حالا می تونم برای مرتب سازی اون Collection متد Sort را صدا بزنم.
این روش برای Array و ArrayList و List کار میده.
اینجاست که آدم به زیبایی interface ها پی می بره.
این هم نمونه مثال خود MSDN هست(هرچند به نظر می تونست بهتر از اینها هم باشه):
using System;
using System.Collections;
public class Temperature : IComparable
{
// The temperature value
protected double temperatureF;
public int CompareTo(object obj) {
Temperature otherTemperature = obj as Temperature;
if (otherTemperature != null)
return this.temperatureF.CompareTo(otherTemperature.tempe ratureF);
else
throw new ArgumentException("Object is not a Temperature");
}
public double Fahrenheit
{
get
{
return this.temperatureF;
}
set {
this.temperatureF = value;
}
}
public double Celsius
{
get
{
return (this.temperatureF - 32) * (5.0/9);
}
set
{
this.temperatureF = (value * 9.0/5) + 32;
}
}
}
public class CompareTemperatures
{
public static void Main()
{
ArrayList temperatures = new ArrayList();
// Initialize random number generator.
Random rnd = new Random();
// Generate 10 temperatures between 0 and 100 randomly.
for (int ctr = 1; ctr <= 10; ctr++)
{
int degrees = rnd.Next(0, 100);
Temperature temp = new Temperature();
temp.Fahrenheit = degrees;
temperatures.Add(temp);
}
// Sort ArrayList.
temperatures.Sort();
foreach (Temperature temp in temperatures)
Console.WriteLine(temp.Fahrenheit);
}
}
// The example displays the following output to the console (individual
// values may vary because they are randomly generated):
// 2
// 7
// 16
// 17
// 31
// 37
// 58
// 66
// 72
// 95





پاسخ با نقل قول
