比方说,你有两个类汽车和大猩猩。这两个类没有任何关系。但是,让我们假设你也有一个可以粉碎事物的课程。而不是定义,需要一个车,并粉碎,然后有一个单独的方法,它是猩猩,它粉碎的方法,可以使称为ICrushable接口...
interface ICrushable
{
void MakeCrushingSound();
}
现在你可以有你的车,你的大猩猩实施ICrushable和您的爱车实现然后ICrushable和你的破碎机上ICrushable,而不是一辆车,一个大猩猩操作...
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(); // get the ICrushable-ness of a Car
ICrushable g = new Gorilla(); // get the ICrushable-ness of a Gorilla
Crusher.Crush(c);
Crusher.Crush(g);
}
和中提琴!你有一台粉碎机可以粉碎汽车并获得“紧缩”!并可以粉碎大猩猩并获得“Squish!”。无需经过查找Cars和Gorillas之间的类型关系以及编译时类型检查(而不是运行时切换语句)的过程。
现在,考虑一些不那么愚蠢的事情......一个可以比较的类(例如IComparable)。这个类将定义你如何比较它的两个类型。
每个评论:好吧,让我们来做吧,这样我们可以对大猩猩数组进行排序。首先,我们添加一些东西来进行排序,比如重量(请忽略按重量排序大猩猩的可疑业务逻辑......在这里不重要)。然后,我们实现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));
}
}
通知我们“得到了各地”的single inheritance的限制,许多语言都有。我们被允许实现尽可能多的接口。现在,通过这样做,我们可以使用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 });
我的大猩猩得到分类和二进制搜索查找匹配的大猩猩与850
很好的例子,但是对于一个叫做Firearm的抽象基类也是如此(这会在上下文中更有意义)。 – 2009-06-27 02:56:51
当然,接口可以在抽象基类中定义。这就是你用C++定义接口的方式,它没有单独的接口语法。 – dewtell 2009-06-27 03:06:17