在vb.Net中实现继承的通用接口

时间:2011-11-29 04:19:04

标签: vb.net generics inheritance interface

在我们当前的项目中,我使用的是通用接口iService,它由所有其他服务接口继承。例如,IService继承了ILogService

然后由LogService实现ILogService接口,如下所示:

Public Interface IService(Of T)
    Sub Save(ByVal T As IEntity)
    Sub Remove(ByVal T As IEntity)
    Function FindBy(ByVal Id As Guid) As T
    Function FindAll() As IEnumerable(Of T)
End Interface

Public Interface ILogService
    Inherits IService(Of Log)


    Function FindLogsByOwner(ByVal Owner As Guid, ByVal visibility As LogVisibility) As IList(Of Log)
    Function FindAllLogsByVisibility(ByVal visibility As LogVisibility) As IList(Of Log)
    Function FindAllLogsByType(ByVal type As LogType) As IList(Of Log)

End Interface

Public Class LogService
    Implements ILogService


    Public Function FindAll() As System.Collections.Generic.IEnumerable(Of Model.CSLS.Log) Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).FindAll

    End Function

    Public Function FindBy(Id As System.Guid) As Model.CSLS.Log Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).FindBy

    End Function

    Public Sub Remove(T As Infrastructure.Domain.IEntity) Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).Remove

    End Sub

    Public Sub Save(T As Infrastructure.Domain.IEntity) Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).Save

    End Sub

    Public Function FindAllLogsByType(type As Model.CSLS.LogType) As System.Collections.Generic.IList(Of Model.CSLS.Log) Implements Model.CSLS.ILogService.FindAllLogsByType

    End Function

    Public Function FindAllLogsByVisibility(visibility As Model.CSLS.LogVisibility) As System.Collections.Generic.IList(Of Model.CSLS.Log) Implements Model.CSLS.ILogService.FindAllLogsByVisibility

    End Function

    Public Function FindLogsByOwner(Owner As System.Guid, visibility As Model.CSLS.LogVisibility) As System.Collections.Generic.IList(Of Model.CSLS.Log) Implements Model.CSLS.ILogService.FindLogsByOwner

    End Function
End Class

需要帮助:我想了解一下,当我实现ILogService接口时,我仍然会在LogService类中获取包含以下内容的函数/ subs:

  • 类型T的方法参数IEntity,而不是Log

如何更新方法签名,以便T显示为Log

我做错了什么?

2 个答案:

答案 0 :(得分:3)

你在谈论这些吗?

Sub Save(ByVal T As IEntity)
Sub Remove(ByVal T As IEntity)

这非常令人困惑,因为在上述方法中,T是方法参数的名称不是泛型类型参数。它可以很容易地foobar。在每种情况下,T的类型都是IEntity

如果这里的意图是SaveRemove应该接受T类型的参数,但该类型T必须实现IEntity,您可以这样表达:

Public Interface IService(Of T As IEntity)
    Sub Save(ByVal entity As T)
    Sub Remove(ByVal entity As T)
    Function FindBy(ByVal Id As Guid) As T
    Function FindAll() As IEnumerable(Of T)
End Interface

答案 1 :(得分:0)

@DanTao是正确的,如果这是意图。但是,如果您只想要通用类型指定方法参数的名称,那是不可能的。

但是,您可以在实现方法中指定您喜欢的任何名称,因此您可以根据需要使用Log,但不能强制执行(并且某些FxCop规则将警告您没有使用接口中指定的相同参数名称。