具有不同签名的类似类

时间:2009-08-18 17:22:09

标签: vb.net .net-2.0

我有两个班级:


    Public Class Subscribing

    Private _subscribingObjects As IList(Of String)

    Public Sub Add(ByVal obj As SubscribeObject)
        '...code...'
    End Sub

    Public Sub Remove(ByVal index As Integer)
        '...code...'
    End Sub

    End Class

    Public Class Providing

    Private _providingObjects As IList(Of String)

    Public Sub Add(ByVal obj As ProvideObject)
        '...code...'
    End Sub

    Public Sub Remove(ByVal index As Integer)
        '...code...'
    End Sub

    End Class

有更优雅的方式来添加吗?一个类就足够了,但由于Add方法有不同的参数,所以一个真的不行。

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:4)

此?

Public Class SubscribingProviding(Of t)

Private _subscribingObjects As IList(Of String)

Public Sub Add(ByVal obj As t)
    '...code...'
End Sub

Public Sub Remove(ByVal index As Integer)
    '...code...'
End Sub

End Class

答案 1 :(得分:1)

你的添加功能应该没问题。只要传入不同的变量类型,就可以使函数名相同。您的删除子类将不允许在同一个类中,因为它使用相同的参数Integer。

答案 2 :(得分:0)

呃..可能不是。它们不同,甚至无法与它们接口。

答案 3 :(得分:0)

我个人不会在一个班级中混合(订阅和提供)两个职责。只需继承List(Of T)

,就可以轻松简化类本身
Public Class Subscribing
    Inherits List(Of SubscribeObject)
End Class

Public Class Providing
    Inherits List(Of ProvideObject)
End Class

如果你真的想要进入一个类并确保它只能分别接受 SubscribeObject ProvideObject ,那么在 SubscribeObject中实现一个公共接口 ProvideObject 。然后创建一个接受接口的泛型类:

' Common interface '
Public Interface ISubscribeProvideObject
End Interface

' SubscribeObject and ProvideObject both implementing the common interface '
Public Class SubscribeObject
    Implements ISubscribeProvideObject
    '...'
End Class

Public Class ProvideObject
    Implements ISubscribeProvideObject
    '...'
End Class

' Generic class accepting both types '
Public Class SubscribingProviding(Of T As ISubscribeProvideObject)
    Inherits List(Of T)
    '... Add() and Remove() methods only needed if custom logic applies ...'
End Class