界面的使用,实际和现实世界的例子

本文关键字:世界 界面 | 更新日期: 2024-09-20 02:07:42

我一直在努力理解接口到底是什么,理论上我已经很好地理解了这个定义。但当谈到实际使用它们时,我会想到一些问题。

大多数资源都是这样定义接口的:

“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;
    }   
}

现在我必须有一个类使用了这个蓝图或契约。那么,在一张纸上写这个蓝图和制作一个界面有什么区别呢?

界面的使用,实际和现实世界的例子

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

当然,如果在使用该接口之前,您已经有了唯一一个将实现该接口的类,那么该接口对您没有好处,但如果您还没有编写实现呢(还要考虑有多个类型正在实现该接口)?

一个简单的例子是编写一个简单Sort方法。我可以为每一种可能的数据类型编写一个Sort实现,也可以编写一个排序方法,假设每一项都实现了IComparable接口,并且可以对其自身进行比较。然后,我的Sort方法可以在编写要比较的对象之前很久就使用该接口编写代码

Servy的回答是一个可靠的解释,但正如您所要求的示例一样,我将使用您的接口并将其扩展到一个可以想象的(如果有点人为的)场景中。

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

// 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,您就可以将它们传递给您的测试执行器。