【问题标题】:Use of interfaces, practical and real world example使用接口,实际和现实世界的例子
【发布时间】: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

标签: c# interface


【解决方案1】:

优点是您可以编写接口,并在任何人编写接口实现之前编写使用接口的代码

当然,如果您在使用该接口之前已经有唯一的实现接口编码的类,那么接口对您没有好处,但是如果您还没有编写实现怎么办(还要考虑以下情况实现接口的类型不止一种)?

一个简单的例子是编写一个简单的Sort 方法。我可以为每一种可能的数据类型编写一个Sort 实现,或者我可以编写一个排序方法,假设每个项目都实现一个IComparable 接口并且可以比较自己。然后我的Sort 方法可以使用该接口编写代码早在您编写要比较的对象之前

【讨论】:

  • 你的回答让我想到了泛型,我想现在我知道如何利用接口了 :) 我会接受你的回答
  • @Servy 但 IComparable 不是一个不包含 implementation 的接口,所以从 IComparable 继承的每个类型都会定义它自己的比较实现?
【解决方案2】:

Servy 的回答是一个可靠的解释,但是 - 正如您所要求的示例 - 我将采用您的界面并将其扩展到一个可以想象的(如果稍微做作)场景。

假设您的接口ITest 已就位(在我的示例中,我偷偷切换SomeTestMethod 以返回一个布尔值)。我现在可以有两个不同的类:

// Determines whether an int is greater than zero
public class GreaterThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable > 0;
    }
}

// Determines whether an int is less than zero
public class LessThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable < 0;
    }
}

现在假设我们有一个单独的类来运行测试。我们可以有以下方法:

public bool RunTest(ITest test)
{
    return test.SomeTestMethod();
}

也许这个方法被这个类的其他成员调用,旨在批量运行测试、产生统计数据等。

现在,您可以创建各种“测试”类。这些可以任意复杂,但是 - 只要它们实现 ITest - 您将始终能够将它们传递给您的测试执行者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 2012-08-17
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多