类/结构以实现递归接口

时间:2019-02-25 22:37:14

标签: .net vb.net generics

我需要一个接口,该接口包括以相同接口类型作为参数的函数。有可能吗?

基本上是这样的:

Public Interface ICopiable
    Sub CopyFrom(ByVal MyObject As ICopiable)
End Interface

Public Structure User
    Implements ICopiable

    Public Property Name As String
    Public Property Surname As String

    '# Copy all Member values from another Structure of same Type
    Public Sub CopyFrom(MyUser As User) Implements ICopiable.CopyFrom
        Me.Name = MyUser.Name
        Me.Surname = MyUser.Surname
    End Sub

End Structure

此刻,我在Implements ICopiable.CopyFrom上遇到以下错误:

  

'CopyFrom'无法实现'CopyFrom',因为接口'ICopiable'上没有匹配的Sub

我认为这与循环引用有关,在循环引用中,Sub被识别为{{之后,ICopiable的自变量将仅被识别为User接口。 1}}接口,只有接受ICopiable参数后,该接口才会发生。

除了用Sub代替Interface以外,是否有其他解决方法?可能是演员吗?

object

编辑

我认为我的思维过程存在缺陷:Public Interface ICopiable Sub CopyFrom(ByVal MyObject As Object) End Interface 只能从相同类型的对象进行复制。

也就是说,仅CopyFrom(),而我定义User.CopyFrom(User)的方式说为Interface,即User.CopyFrom(AnyICopiable)说接受Interface是可以接受的。这是错误的。

2 个答案:

答案 0 :(得分:3)

我认为这就是您所需要的:

Public Interface ICopyable(Of T As ICopyable(Of T))

    Sub CopyFrom(source As T)    

End Interface

Public Structure User
    Implements ICopyable(Of User)

    Public Property Name As String
    Public Property Surname As String

    Public Sub CopyFrom(source As User) Implements ICopyable(Of User).CopyFrom
        Me.Name = source.Name
        Me.Surname = source.Surname
    End Sub

End Structure

这几乎是实现IComparable(Of T)之类的接口的方式,例如String类和Integer结构分别实现IComparable(Of String)IComparable(Of Integer)。话虽如此,我不确定此类接口是否具有通用类型约束,因此从理论上讲,一个类型可以实现为与其他类型可比。在这种情况下,约束(即As ICopyable(Of T)部分)可确保只能从同一类型的另一个实例复制实现该接口的类型。

编辑:

如果您已经有这样的方法:

Public Sub DoSomething(copyable As ICopyable)
    '...
End Sub
您要这样呼叫的

Dim user2 As User

user2.CopyFrom(user1)
DoSomething(user2)

然后,要使用我的解决方案,只需将方法更改为如下所示:

Public Sub DoSomething(Of T As ICopyable(Of T))(copyable As T)
    '...
End Sub

,呼叫将保持完全相同。您仍然可以调用该方法,并传递实现ICopyable(Of T)接口的任何对象。与大多数常规方法调用一样,T将通过用法来推断。

答案 1 :(得分:0)

没有泛型的解决方案可以做到这一点,但是我想尽可能避免:

Public Interface ICopiable
    Sub CopyFrom(ByVal MyObject As Object)
End Interface

Public Structure User
    Implements ICopiable

    Public Property Name As String
    Public Property Surname As String

    '# Copy all Member values from another Structure of same Type
    Public Sub CopyFrom(Of T as ICopiable)(MyUser As Object) Implements ICopiable.CopyFrom
        If Not TypeOf MyUser Is User Then Throw New ArgumentException("Object Type must be User", "MyUser")
        Me.Name = MyUser.Name
        Me.Surname = MyUser.Surname
    End Sub

End Structure