, . . , , , . , , , , , Gorilla , ICrushable...
interface ICrushable
{
void MakeCrushingSound();
}
ICrushable, - ICrushable, ICrushable Car and Gorilla...
public class Crusher
{
public void Crush(ICrushable target)
{
target.MakeCrushingSound();
}
}
public class Car : ICrushable
{
public void MakeCrushingSound()
{
Console.WriteLine("Crunch!");
}
}
public class Gorilla : ICrushable
{
public void MakeCrushingSound()
{
Console.WriteLine("Squish!!");
}
}
static void Main(string[] args)
{
ICrushable c = new Car();
ICrushable g = new Gorilla();
Crusher.Crush(c);
Crusher.Crush(g);
}
! , "Crunch!". "Squish!". ( ).
- ... , (IComparable). , .
: , , Gorillas. -, -, , , (, - Gorillas ... ). ICompararble...
public class Gorilla : ICrushable, IComparable
{
public int Weight
{
get;
set;
}
public void MakeCrushingSound()
{
Console.WriteLine("Squish!!");
}
public int CompareTo(object obj)
{
if (!(obj is Gorilla))
{
throw (new ArgumentException());
}
var lhs = this;
var rhs = obj as Gorilla;
return (lhs.Weight.CompareTo(rhs.Weight));
}
}
, "" , . , . , , , 10 , (Array.Sort, Array.BinarySearch). ...
var gorillas = new Gorilla[] { new Gorilla() { Weight = 900 },
new Gorilla() { Weight = 800 },
new Gorilla() { Weight = 850 }
};
Array.Sort(gorillas);
var res = Array.BinarySearch(gorillas,
new Gorilla() { Weight = 850 });
My Gorillas , Gorilla 850.