可能重复:
What are some advantages to using an interface in C#?界面概念
为什么我们正在使用的接口在C#。什么是使用接口的优势。你能解释一下这个概念吗?容易理解,也是简单的接口例子吗?
可能重复:
What are some advantages to using an interface in C#?界面概念
为什么我们正在使用的接口在C#。什么是使用接口的优势。你能解释一下这个概念吗?容易理解,也是简单的接口例子吗?
接口是一种将接口与实现分离的方法。
你可以说这里是一个函数,它给了我第n个素数。这是界面。如果我是一个用户,我不在乎你如何计算它 - 所以我只需要接口。
此外,接口还为多重继承提供了一种选择 - 您只能拥有一个基类,但可以实现多个接口。
实施例:
interface IPrimeComputer {
int GetNPrime(int n);
}
class SieveComputer : IPrimeComputer {
public int GetPrime(int n) {
//compute the nth prime using a sieve
}
}
class MagicComputer : IPrimeComputer {
public int GetPrime(int n) {
//compute the nth prime using some magic that no one else can understand.
}
}
...
IPrimeComputer computer = new MagicComputer();
int nprime = computer.GetPrime(100);
computer = new SieveComputer();
nprime = computer.GetPrime(100);
这解释了“什么”并不是真正的“为什么”。另外,要说接口本身提供多重继承是有点误导。你不会从接口继承任何东西,这是一个指定你必须实现的合约。你可以说,接口使自己更倾向于多态而不是继承。 –
同意@Evil Pigeon。我认为这个问题是关于“为什么”。 –
见本SO问题为接口What are some advantages to using an interface in C#?优点
的接口的一个简单的例子可以是:
public interface IAnimal
{
void Sleep();
void Run();
void Talk();
}
接口然后将通过实施类,它将执行界面中指定的方法:
public class Dog : IAnimal
{
public void Talk()
{
Console.WriteLine("Ruff!");
}
public void Run()
{
Console.WriteLine("The dog runs after balls and cars.");
}
public void Sleep()
{
Console.WriteLine("ZZZZZZZZZZ");
}
}
和不同的类将有不同的实现方法相同:
public class Cat : IAnimal
{
public void Talk()
{
Console.WriteLine("Meow");
}
public void Run()
{
Console.WriteLine("The cat looks at you and says, 'Yeah, right...'");
}
public void Sleep()
{
Console.WriteLine("All the time - what else does a cat do?");
}
}
这些都是简单的例子,但应该给你一个想法。
是的,界面触及了C#不支持多继承的事实,但这不是您应该使用接口的原因。正如Peter所说,这是一种分离对象实现和对象能力的方式。接口定义了你可以用一个对象(能力)做什么,但对象的实现定义了你如何做到这一点。
假设您正在制作一个图形程序,将图形打印到要旋转的屏幕上。然后你可能有一个接口IShape
,它定义了方法Rotate
和Draw
,但这些方法的真正实现在于类Rectangle
,Circle
等等,因为你很可能想要使用多个形状。
实现一个接口说嘿!看着我!我可以做这个。
接口借给自己对许多应用:
一个好处是,实现接口的类别别无选择,只能以自己的方式实现接口的方法。
所以,如果你是界面的创建者,而其他程序员需要从他们自己的类中实现它,那么这些类将具有来自界面的模式。
网上有很多教程解释this.do你有任何具体的.. –
你的问题,是一般性的问题,有太多不同的答案。 http://stackoverflow.com/questions/5661876/what-is-the-advantage-of-using-interface – Peyman