受保护在VB.Net中设置接口中定义的属性

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

public interface IPersistable { T Id { get; } } 

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

 public class Foo : IPersistable { public int Id { get; protected set; } } 

但是,我无法获得任何样本的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 

…将无法编译,但这会:

 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 

我很欣赏这个例子过于简单,并且可能通过受保护的构造函数更好地实现,但我感兴趣的是它是否可以这种方式完成?

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

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

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

 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 

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

它目前不支持该语言,也不支持Visual Basic 10(即使用Visual Studio 2010的版本)。 有一个愿望清单项目正是如此 。 在此之前,nobugz建议的解决方法是唯一的选择。

从Visual Basic 14开始 ,您的第一个VB代码示例编译得很好。

接口属性只能由匹配的类属性实现。 在vb.net和C#中都是如此。 这两种语言的不同之处在于,如果可以使用同名的公共读写属性,C#的隐式接口实现function将自动定义只读或只写属性来实现接口。