0

I am trying to learn OOP concept at an advance level. I was reading through the topic interfaces and have a confusion. But first, let me show you what exactly caused this confusion.
I tested this Code Sample. but I am confused with the use of interfaces. After implementing that code, it seems to me that I can call the method DoFirst from class A by simply creating an instance of it. so why use an interface at first place?

Something like this:

A myA = new A();
myA.DoFirst();

and similiarly,

B myB = new B();
myB.DoFirst();

In both the classes, i have to implement a method called 'DoFirst', so what good does interface provided to me?

Can't I just write these methods in different classes myself?

my Second question, say I have an interface that has 5 methods. If a class implements it, and only wants to provide implementation of 3 methods instead of writing code of all 5 methods supplied by the interface. Isn't this useless? why have access methods that i don't want?

can somebody answer these with example (Highly appreciated) please?

4

3 回答 3

3

您提供的链接中已经指出了优势......基本上你也可以写

void DoSomething(IMyInterface obj)
{
    obj.DoFirst();
}

然后发送实现该接口的任何类型的对象作为参数。

A myA = new A();
DoSomething(myA);
B myB = new B();
DoSomething(myB);

该方法DoSomethig不关心对象的类型,只要它公开一个名为IMyInterface.

于 2013-02-22T11:59:18.120 回答
2

一些现实生活中的例子——也是使用接口的另一种方式/原因。

在我自己的代码中,我有一个引擎,它处理代码以在 Excel 中生成报告。在这个引擎中,我必须以两种不同的方式编写代码,一种使用 Microsoft Excel Interop,另一种使用 Open Office Interop。我没有复制我的整个引擎以两种不同的方式工作,或者在所有实际的互操作函数中编写大量 if 语句,而是实现了一个接口。然后我声明了两个类,每个类都实现了接口,但是一个使用Excel,另一个使用open office。然后,在我的代码中,我简单地引用了接口及其函数,并在函数的最开始使用一个 if 语句来告诉接口要实现哪个类。

public class ExcelEngineInterop : ISSinterface
{ ... }

public class OOEngineInterop : ISSinterface
{ ... }

//cant use two variables with the same name, so use 1 interface reference instead
ISSinterface ssInt;
if(ExcelFlag)
    ssInt = new ExcelEngineInterop();
else
    ssInt = new OOEngineInterop();

//two VERY different functions between Excel and OpenOffice.
ssInt.OpenApp();
ssInt.OpenFile(fileName);

//etc etc and so on

这是使用接口的另一个原因。当您需要一个代码块根据某些外部标志执行两种(或更多)不同的方式时。

另一个例子。

有一个顶级表单,其下有许多自定义用户控件。用户触发表单级事件,例如按钮单击,但根据哪些用户控件处于活动状态以及单击发生时它们上的设置,控件本身需要做一些不同的事情。与其编写大量的 if 语句来确保每个语句从顶层正确运行,不如在每个控件上实现一个接口,然后执行以下操作:

public ButtonClick(object sender, EventArgs e)
{
    //note: I dont know which of my classes currentrightcontrol belongs to at the moment.
    //      it could be any one of 22 different controls. It must be cast to something
    //      in order to call the ButtonClick method (its actual type is generic "UserControl"

    IMyRunControl ctrl = CurrentRightControl as IMyRunControl;
    ctrl.FormButtonClicked();
}
于 2013-02-22T12:09:13.147 回答
0

C# 是一种静态类型语言(至少除非你明确告诉它不是)。这意味着编译器使用变量的类型来知道被引用的对象是否有你将要使用的成员。

因此,该接口为编译器(以及其他程序员)提供了该类实现该接口的协定。因为接口可以在没有层次关系的类之间共享,这意味着您可以通过在参数类型中定义该接口来定义一个可以将对象作为参数的方法。

于 2013-02-22T11:55:13.747 回答