VB.Net中的受保护集,用于在接口中定义的属性

Row*_*haw 5 .net c# vb.net properties c#-to-vb.net

我们有一个界面,可以大致简化为:

public interface IPersistable<T>
{
    T Id { get; }
}
Run Code Online (Sandbox Code Playgroud)

大多数实现接口的地方都想拥有它,以便在该属性上有一个受保护或私有的集合,即在C#中:

public class Foo : IPersistable<int>
{
    public int Id { get; protected set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,我无法获得任何样本的VB.Net代码,这些代码遵循相同的模式,同时仍然实现了接口,因此:

Public Class Foo
    Implements IPersistable(Of Integer)

    Public Property Id() As Integer Implements IPersistable(Of Integer).Id
        Get
            Throw New NotImplementedException()
        End Get
        Protected Set(ByVal value As Integer)
            Throw New NotImplementedException()
        End Set
    End Property
End Class
Run Code Online (Sandbox Code Playgroud)

...不会编译,但这会:

Public Class Foo
    Public Property Id() As Integer
        Get
            Throw New NotImplementedException()
        End Get
        Protected Set(ByVal value As Integer)
            Throw New NotImplementedException()
        End Set
    End Property
End Class
Run Code Online (Sandbox Code Playgroud)

我很欣赏这个例子过于琐碎,并且可能通过受保护的构造函数更好地实现,但我感兴趣的是它是否可以这样做?

[编辑:] ...显然,如果一个类型想要使用XMLSerialization,那么属性需要是公共读/写,或者类型需要为每个类型编写自定义序列化器.

从本质上讲,我认为界面应该定义最小的可访问性,但VB将其解释为确切的可访问性?

Han*_*ant 6

是的,你必须按字面意思实现接口.一种可能的解决方法是使用其他名称在类中重新发布该属性:

Public Class Foo
  Implements IPersistable(Of Integer)
  Private m_Id As Integer

  Public ReadOnly Property Id() As Integer Implements IPersistable(Of Integer).Id
    Get
      Return m_Id
    End Get
  End Property

  Protected Property IdInternal() As Integer
    Get
      Return m_Id
    End Get
    Set(ByVal value As Integer)
      m_Id = value
    End Set
  End Property
End Class
Run Code Online (Sandbox Code Playgroud)

如果要在派生类中覆盖它,则声明属性Overridable.