我需要和你讨论一件事。我一直在读到这个接口,它是类之间的契约,类将提供接口,实现接口的所有方法。为了解决著名的钻石问题,我们有接口。如(我使用的是C#)
public interface IAInterface
{
void aMethod();
}
public interface IBInterface
{
void aMethod();
}现在
public class aClass : IAInterface, IBInterface
{
public void aMethod()
{
}
} 通过上面的代码,可以说aClass已经提供了接口的两种方法的实现。我的困惑是:如果它是类和接口之间的协定,那么我们怎么能说这两个接口的协定都得到了履行呢?
一个真实的例子,比如我和杰克签订了合同,我将给他5美元,同时我也和本签订了合同,我将给他5美元,现在通过向他们中的一个(杰克或本)提供5美元,我怎么能说我已经履行了与他们两个人的合同呢?
我的问题可能看起来很幼稚,但这让我很困惑。
发布于 2012-08-27 18:00:15
接口保证将实现一组给定的方法。接口本身并不关心代码将如何实现。与扩展类相反,当您扩展一个类时,您正在使用一些预定义的代码。
如果您使用相同的方法扩展两个类,例如methodA,并调用此方法,则编译器将不知道需要运行哪个方法。另一方面,当您使用相同的方法实现两个接口时,由于实现是在您自己的代码中编写的,因此编译器将知道它需要在哪里找到实现。
因此,基本上,当你实现你所保证的东西时,你将提供一些服务。
编辑:我会试着用你的例子,把它变成面向对象的方式,希望这会让事情变得更清楚。
杰克和本将保证他们会借钱给你,而你,另一方面,保证会还钱,所以,从面向对象的角度来看,你可以这样看:
public interface IPay
{
public void Pay(Individual i);
}
public class MySelf : IPay
{
public void Pay(Individual i)
{
...
}
}
public interface ILend
{
public void Lend(Individual i);
}
public class Jack : ILend //Same applies for Ben
{
public void Lend(Individual i)
{
...
}
}这就是我将如何处理您指定的问题。
至于另一个垃圾示例,您可以这样做:
public interface ITakeTrash
{
public void TakeTrash(Trash t);
}
public Son : ITakeTrash
{
public void TakeTrash(Trash t);
}
public class Mum //Same applies for dad
{
Son mySon = ...
mySon.TakeTrash(t);
}你的父母都不知道如何处理垃圾,但是,他们知道你知道如何处理它,这就是他们关心的(就像上面一样,你只关心Ben和Jack能不能给你钱,其他人只关心你能不能还钱,没有人真正关心你是怎么做的。
我确实理解你想要做什么,基本上是说,如果我用具有相同名称的方法实现两个不同的接口,做不同的事情会怎么样。如果你遇到过这样的情况,我认为那是由于糟糕的设计造成的。我不建议构建一个做无数不同事情的类,这是原因之一。
另一方面,你可能会问,如果我有两个接口,它们用同名的方法做类似的事情,那会怎么样?然后,我认为答案是,既然接口做的是相似的事情,而你有同名的方法,那么很可能你正在做同样的事情,因此,你不需要混淆自己。
我希望这篇编辑有助于阐明这个问题。
发布于 2012-08-27 17:57:05
好的,实现方法不同于给钱。就像倒垃圾一样。如果你答应爸爸妈妈去倒垃圾,倒一次垃圾就足够了。
发布于 2016-05-05 17:58:56
举个例子,我们有两个接口,它们都有相同的函数PrintIt,类MyClass实现了这两个接口。
interface IAInterface
{
void PrintIt(string s);
}
interface IBInterface
{
void PrintIt(string s);
}
class MyClass : IAInterface, IBInterface
{
public void PrintIt(string s)
{
Console.WriteLine(s);
}
}可以通过引用多个接口
MyClass _class = new MyClass();
_class.PrintIt("Class");
IAInterface _aInterface = (IAInterface)_class;
_aInterface.PrintIt("IAInterface");
IBInterface _bInterface = (IBInterface )_class;
_bInterface.PrintIt("IBInterface");您还可以提供显式接口实现...
class MyClass : IAInterface, IBInterface
{
public void IAInterface.PrintIt(string s)
{
Console.WriteLine("AInterface - {0}", s);
}
public void IBInterface.PrintIt(string s)
{
Console.WriteLine("BInterface - {0}", s);
}
}https://stackoverflow.com/questions/12139772
复制相似问题