VB.NET 中的接口继承:我在实现中引用哪一个?

问题描述 投票:0回答:2

我正在 Visual Studio 2015 中使用 Visual Basic .NET,我想知道以下内容。假设我有两个接口,名为

InterfaceA
InterfaceB
,其中
InterfaceB
继承自
InterfaceA
,如下所示:

Public Interface InterfaceA
    Property A As String ' Type not important here.
End Interface

Public Interface InterfaceB
    Inherits InterfaceA

    Property B As Integer ' Type not important here, either.
End Interface

现在我要创建一个名为

InterfaceBImplementer
的类,它(顾名思义)实现
InterfaceB
:

Public Class InterfaceBImplementer
    Implements InterfaceB

    Public Property B As Integer Implements InterfaceB.B
        Get
            ' Snip.
        End Get
        Set(value As Integer)
            ' Snip.
        End Set
    End Property

' To be continued...

到目前为止,一切都很好。属性

B
只能在
InterfaceB
中找到,所以不存在它来自哪里的问题。

但是,

InterfaceB
A
继承属性
InterfaceA
A
InterfaceBImplementer
的以下两种实现似乎都是有效的:

' Referring to InterfaceA.
Public Property A As String Implements InterfaceA.A
    Get
        ' Snip.
    End Get
    Set(value As String)
        ' Snip.
    End Set
End Property

或:

' Referring to InterfaceB.
Public Property A As String Implements InterfaceB.A
    Get
        ' Snip.
    End Get
    Set(value As String)
        ' Snip.
    End Set
End Property

我应该选择哪一个?两者之间有什么区别,或者没有关系吗?如果两者相同,在这种情况下我应该遵循什么约定或最佳实践?

vb.net inheritance interface
2个回答
1
投票

这是

Public Property A As String Implements InterfaceB.A
,因为您即将实现被转换为
InterfaceBImplementer
类的接口。


0
投票

由 Visual Studio 自动生成的代码的形式为

Public Property A As String Implements InterfaceA.A
;它选择声明属性的接口,而不是最派生的接口。

我不知道 Visual Studio 在这里的决定是否使其成为更好的选择,但我坚持使用 VS 编辑器的行为,以便我的代码保持一致,而不需要编辑一堆自动生成的声明。

© www.soinside.com 2019 - 2024. All rights reserved.