Реализация 2 интерфейсов со свойствами «Одно имя» - PullRequest
9 голосов
/ 10 февраля 2009

Это кажется разумным (и, может быть, простым?) Сценарием, но как бы вы поступили следующим образом:

Допустим, у меня есть 2 интерфейса:

Interface ISimpleInterface
    string ErrorMsg { get; } 
End Interface

Interface IExtendedInterface
    string ErrorMsg { get; set; }    
    string SomeOtherProperty { get; set; }
End Interface

Я хочу, чтобы класс реализовывал оба интерфейса:

Public Class Foo Implements ISimpleInterface, IExtendedInterface

Как определить свойство ErrorMsg в классе, учитывая, что каждый интерфейс имеет свой уровень доступа?

Вот мой сценарий на случай, если вам интересно: я пишу UserControl, используя архитектуру psuedo MVC, где UserControl предоставляет расширенный интерфейс своему контроллеру и предоставляет простой интерфейс потребителям элемента управления.

Между прочим, реализация этого в VB.NET (любой предложенный synatx в vb приветствуется).

Ответы [ 8 ]

6 голосов
/ 10 февраля 2009

Извините, но я не осваиваю синтаксис VB.Net.

В C # вы можете реализовывать интерфейсы неявно или явно. Если ваш класс Foo реализует ErrorMsg как открытый метод, эта реализация будет использоваться для обоих интерфейсов.

Если вам нужна отдельная реализация, вы можете реализовать ее явно:

string ISimpleInterface.ErrorMsg {get { ... } } 
string IExtendedInterface.ErrorMsg {get { ... } set { ... }} 
5 голосов
/ 10 февраля 2009

Вы можете реализовать один из них или оба интерфейса с реализацией «явного интерфейса», чтобы компилятор знал, какое свойство ErrorMsg принадлежит какому интерфейсу.

Для этого просто напишите: ISimpleInterface (для C #) после имени вашего класса, затем нажмите ISimpleInterface и выберите реализовать явный интерфейс.

Больше информации здесь: http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx

3 голосов
/ 10 февраля 2009

В C # неявная реализация (с set) может удовлетворить оба из них:

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

Если вы хотите изменить его, вы можете использовать явную реализацию («Реализации» в VB?) - в C #:

string ISimpleInterface.ErrorMsg
{
    get { return ErrorMsg; } // or something more interesting
}
2 голосов
/ 10 февраля 2009

Ключевое слово Implements в VB.NET упрощает:

Public Interface ISimpleInterface
  ReadOnly Property ErrorMsg() As String
End Interface

Friend 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 ErrorMsgEx() As String Implements IExtendedInterface.ErrorMsg
    Get
      Return msg
    End Get
    Set(ByVal value As String)
      msg = value
    End Set
  End Property

  Public Property SomeOtherPropertyEx() As String Implements IExtendedInterface.SomeOtherProperty
    Get
      Return other
    End Get
    Set(ByVal value As String)
      other = value
    End Set
  End Property

  Public ReadOnly Property ErrorMsg() As String Implements ISimpleInterface.ErrorMsg
    Get
      Return msg
    End Get
  End Property
End Class
2 голосов
/ 10 февраля 2009

В C # вы можете использовать явную реализацию интерфейса:

class Foo
{
    string ISimpleInterface.ErrorMsg
    { get... }

    string IExtendedInterface.ErrorMsg
    { get... set... }

    string IExtendedInterface.SomeOtherProperty
    { get... set... }
}

или Отображение интерфейса

class Foo
{
    public string ErrorMsg
    { get... set... }       

    public string SomeOtherProperty
    { get... set... }
}

Что касается VB.NET, он имеет ключевое слово Implements:

Property ErrorMsg As String Implements ISimpleInterface.ErrorMsg

Property OtherErrorMsg As String Implements IExtendedInterface.ErrorMsg
0 голосов
/ 10 февраля 2009

Хотя явная реализация решит эту проблему, как показали другие, в этом самом случае я бы, вероятно, позволил IExtendedInterface реализовать ISimpleInterface (свойство ErrorMsg семантически совпадает со свойством, оно означает то же самое в этих двух интерфейсах, как я предполагаю).

interface ISimpleInterface
{
    string ErrorMessage { get; set; }
}
interface IExtendedInterface : ISimpleInterface
{
    string SomeOtherProperty { get; set; }
}
0 голосов
/ 10 февраля 2009

Вы можете иметь частные подпрограммы, реализующие интерфейсы. Он доступен только тогда, когда объект назначен переменной этого типа интерфейса.

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 голосов
/ 10 февраля 2009

Вам нужно будет работать с явными реализациями интерфейса. Больше по теме здесь: http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...