Implementing an Interface with Child Classes

2019-08-26 02:47发布

I have the following interfaces:

Interface IViewModel
    ...
End Interface

Interface ISpecialViewModel
    Inherits IViewModel
    ...
End Interface

Interface IView
    WriteOnly Property MyViewModel As IViewModel
End Interface

Following are my classes:

Class VerySpecialViewModel
    implements ISpecialViewModel
    ...
End Class

Class View
    Implements IView

    Public WriteOnly Property MyViewModel As VerySpecialViewModel Implements IView.MyViewModel 
        ...
    End Property
End Class

It tells me that 'MyViewModel' cannot implement 'MyViewModel' because there is no matching property on interface 'IView'.

1条回答
三岁会撩人
2楼-- · 2019-08-26 02:58
Public Interface ISomething
    WriteOnly Property Prop As IParent
End Interface

That interface declaration isn't satisfied by your class implementation. Consider following situation:

There is another interface called IChild2:

Public Interface IChild2
    Inherits IParent
    ...
End Interface

According to ISomething interface you should be able to assign instance of class implementing IChild2 into Thing.Prop, because it inherits IParent.But you can't, because Thing.Prop property is of IChild type and IChild2 does not inherits IChild

Update

What about that solution:

Class ThingBase
    Implements ISomething

    Public WriteOnly Property Prop As IParent Implements ISomething.Prop
        Set(value As IParent)

        End Set
    End Property
End Class

Class Thing
    Inherits ThingBase

    Public Overloads WriteOnly Property Prop As IChild
        Set(value As IChild)
            MyBase.Prop = value
        End Set
    End Property
End Class

Update2

Interface IView(Of T As IViewModel)
    WriteOnly Property MyViewModel As T
End Interface

Class VerySpecialViewModel
    Implements ISpecialViewModel
End Class

Class View
    Implements IView(Of ISpecialViewModel)

    Public WriteOnly Property MyViewModel As ISpecialViewModel Implements IView(Of ISpecialViewModel).MyViewModel
        Set(value As ISpecialViewModel)

        End Set
    End Property
End Class

or

Class View
    Implements IView(Of VerySpecialViewModel)

    Public WriteOnly Property MyViewModel As VerySpecialViewModel Implements IView(Of VerySpecialViewModel).MyViewModel
        Set(value As VerySpecialViewModel)

        End Set
    End Property
End Class
查看更多
登录 后发表回答