2

我了解接口的概念,但是我经常发现很难找到如何使用它们的实际示例。我已经生成了以下代码:

Public MustInherit Class Deletion2
    Implements DeletionInterface2

    Public MustOverride Function Delete() As String Implements DeletionInterface2.Delete
    Public Function CheckDate() As Boolean Implements DeletionInterface2.CheckDate
        Return True
    End Function
End Class

Public Class System1Delete
    Inherits Deletion2
    Implements DeletionInterface2
    Overrides Function Delete() As String
        Return "System 1 Deleted"
    End Function

End Class

Public Class System2Delete
    Inherits Deletion2
    Implements DeletionInterface2
    Overrides Function Delete() As String
        Return "System 2 Deleted"
    End Function

End Class

Public Interface DeletionInterface2
    Function CheckDate() As Boolean
    Function Delete() As String
End Interface

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim IDeletion As DeletionInterface2
        IDeletion = New System1Delete
        IDeletion.CheckDate()
        IDeletion.Delete()
        IDeletion = Nothing

        IDeletion = New System2Delete
        IDeletion.CheckDate()
        IDeletion.Delete()
        IDeletion = Nothing
End Sub

在上面的示例中(在页面加载中),我使用了对接口的引用来创建对象的实例,但我不明白这样做的真正好处。

4

1 回答 1

3

使用像接口(或MustInherit类)这样的抽象的好处是,您可以以完全相同的方式对待任何实现该接口的对象。

例如,System.Data命名空间使用了许多这样的抽象,这意味着实现不同的数据提供者更容易,并且由于核心使用这些抽象,它不需要随着新实现的添加而改变(关于所有不同提供者的东西,内置和第三方 - SQL Server、Oracle、PostGresSQL、MySQL 等)。

于 2012-07-07T20:57:28.763 回答