If an interface defines a ReadOnly Property, how can an implementer provide the Setter to this property?

前端 未结 5 1090
北恋
北恋 2021-01-18 04:51

Is there a way for implementers of an interface where a ReadOnly property is defined to make it a complete Read/Write Property ?

5条回答
  •  无人共我
    2021-01-18 04:59

    In Visual Basic, when you implement a method or property from an interface, you can change its name and its visibility. You can leverage that capability to handle the case you are asking about. Prior to Visual Studio 2015, I often did this:

    Interface:

    Public Interface SomeInterface
        ReadOnly Property SomeProperty As String
    End Interface
    

    Implementing Class:

    Public Class SomeClass
        Implements SomeInterface
    
        Public Property SomeProperty As String
        Private ReadOnly Property SomeProperty_ReadOnly As String Implements SomeInterface.SomeProperty
            Get
                Return Me.SomeProperty
            End Get
        End Property
    End Class
    

    The result is that SomeProperty is read-only when accessed through SomeInterface, but read-write when accessed through SomeClass:

    Dim c As New SomeClass
    c.SomeProperty = "hello" 'Write via class OK
    Dim s1 = c.SomeProperty 'Read via class OK
    
    Dim i As SomeInterface = c
    Dim s2 = i.SomeProperty 'Read via interface OK
    i.SomeProperty = "greetings" 'Syntax Error, interface property is read-only
    

提交回复
热议问题