【发布时间】:2013-12-13 21:51:28
【问题描述】:
我一直在试图理解接口到底是什么,理论上我已经很好地消化了这个定义。但是当谈到实际使用它们时,我想到了一些问题。
大多数资源都是这样定义接口的:
“An interface is a contract between itself and any class that implements it. This contract states that any class that implements the interface will implement the interface's properties, methods and/or events. An interface contains no implementation, only the signatures of the functionality the interface provides. An interface can contain signatures of methods, properties, indexers & events.”
这很容易理解,但我的问题是,如果接口(根据这个定义)是它们与类之间的某种蓝图或契约,如果我定义这个接口,实际会发生什么,
interface ITest {
int SomeTestVariable { set; get;}
int SomeTestMethod ();
}
创建一个实现此接口及其所有方法的类
class Test: ITest {
int SomeTestvariable { set; get;}
int SomeTestMethod () {
return 1;
}
}
在实现了所有方法和属性之后,我将其删除。
class Test {
int SomeTestvariable { set; get;}
int SomeTestMethod () {
return 1;
}
}
现在我必须有一个使用此蓝图或合同的班级。那么在一张纸上写这个蓝图和做一个界面有什么区别呢?
【问题讨论】:
-
考虑一下如果你有一个带有签名
public bool RunTest(ITest test)的方法会发生什么 -
@AntP,你说的很对,实际上这是我的问题,在什么情况下我需要有这样的方法。如果你能提供一个例子,我将不胜感激。
-
一个接口允许您强制执行许多不同的具体对象,所有对象都具有相同的实现。因此,当您食用它们时,您可以确保它们的一致性,并且它们可以来自许多不同的地方......现在@Servy 的答案将胜过我的;D