Implementing 2 Interfaces with 'Same Name' Properties

后端 未结 8 1784
天涯浪人
天涯浪人 2021-01-04 22:50

This seems like a reasonable (and maybe simple?) scenario, but how would you do the following:

Lets say I have 2 interfaces:

Interface ISimpleInterfa         


        
相关标签:
8条回答
  • 2021-01-04 23:23

    You can have private subroutines implement interfaces. It is only exposed when the object is assigned to a variable of that interface type.

    Public Class Form1
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim S As ISimpleInterface
            Dim Ext As IExtendedInterface
            Dim F As New Foo
            F.ErrorMsg = "Test Error"
            S = F
            Ext = F
            MsgBox(S.ErrorMsg)
            MsgBox(Ext.ErrorMsg)
            MsgBox(F.ErrorMsg)
        End Sub
    End Class
    
    
    Public Interface ISimpleInterface
        ReadOnly Property ErrorMsg() As String
    End Interface
    
    Public Interface IExtendedInterface
        Property ErrorMsg() As String
        Property SomeOtherProperty() As String
    End Interface
    
    Public Class Foo
        Implements ISimpleInterface, IExtendedInterface
        Private other As String
        Private msg As String
    
        Public Property ErrorMsg() As String Implements IExtendedInterface.ErrorMsg
            Get
                Return msg
            End Get
            Set(ByVal value As String)
                msg = value
            End Set
        End Property
    
        Public Property SomeOtherProperty() As String Implements IExtendedInterface.SomeOtherProperty
            Get
                Return other
            End Get
            Set(ByVal value As String)
                other = value
            End Set
        End Property
    
        Private ReadOnly Property ErrorMsgSimple() As String Implements ISimpleInterface.ErrorMsg
            Get
                Return ErrorMsg
            End Get
        End Property
    End Class
    
    0 讨论(0)
  • 2021-01-04 23:25

    In C#, an implicit implementation (with the set) can satisfy both of these:

    class Foo : ISimpleInterface, IExtendedInterface
    {
        public string ErrorMsg { get; set; } 
        public string SomeOtherProperty {get; set;}
    }
    

    If you want to change it, you can use explicit implementation ("Implements" in VB?) - in C#:

    string ISimpleInterface.ErrorMsg
    {
        get { return ErrorMsg; } // or something more interesting
    }
    
    0 讨论(0)
提交回复
热议问题