Storing an object that implements multiple interfaces and derives from a certain base (.net)

后端 未结 1 1440
一个人的身影
一个人的身影 2020-12-19 14:23

In .net, it\'s possible to use generics so that a function can accept arguments which support one or more interfaces and derive from a base type, even if there does not exis

相关标签:
1条回答
  • 2020-12-19 15:17

    The best way I can think of is to make an abstract storage and generic implementation of this storage. For example (excuse my VB.NET):

    MustInherit Class Storage
        Public MustOverride Sub DoSomething()
    End Class
    
    Class Storage(Of T As {IInterface1, IInterface2, SomeBaseType})
        Inherits Storage
    
        Public Overrides Sub DoSomething()
            ' do something with Value.
        End Sub
    
        Public Value As T
    End Class
    

    And usage

    Dim S As Storage
    
    Sub Foo(Of T As {IInterface1, IInterface2, SomeBaseType})(ByVal Param As T)
        S = New Storage(Of T) With {.Value = Param}
    End Sub
    
    Sub UseS()
        S.DoSomething();
    End Sub
    

    Update: Ok, because we may not be able identify in advance all of the actions:

    MustInherit Class Storage
        MustOverride ReadOnly Property SomeBaseType As SomeBaseType
        MustOverride ReadOnly Property IInterface1 As IInterface1
        MustOverride ReadOnly Property IInterface2 As IInterface2
    End Class
    
    Class Storage(Of T As {IInterface1, IInterface2, SomeBaseType})
        Inherits Storage
    
        Public Value As T
    
        Public Overrides ReadOnly Property IInterface1 As IInterface1
            Get
                Return Value
            End Get
        End Property
    
        Public Overrides ReadOnly Property IInterface2 As IInterface2
            Get
                Return Value
            End Get
        End Property
    
        Public Overrides ReadOnly Property SomeBaseType As SomeBaseType
            Get
                Return Value
            End Get
        End Property
    End Class
    
    0 讨论(0)
提交回复
热议问题