2010-03-02 68 views
5

我们有接口,可以非常简化为:受保护设置在VB.Net中的接口定义的属性

public interface IPersistable<T> 
{ 
    T Id { get; } 
} 

实现接口的大部分地方想拥有它,这样是有保护或对财产,即私定,在C#:

public class Foo : IPersistable<int> 
{ 
    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将其解释为确切的可访问性?

+1

+1在我注意到VBNET不允许之前,我遇到了同样的情况。 – 2010-03-02 15:31:40

回答

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 

财产申报可重写,如果你打算重写它的派生类。

+0

+1 VBNET不允许在属性getter和setter中修改此属性。您需要重新发布二传手到另一个财产,或有权访问您的私人领域,当然,这将有一个不同的私人修改。这是因为接口需求在写入时需要实现。所以,如果您将您的Id属性标记为公开,而不是将其提及为ReadOnly,则必须同时设置Get和Set Public。 – 2010-03-02 15:31:05

+0

接受,因为我现在发现这是一个愿望清单项目:http://stackoverflow.com/questions/2362381/protected-set-in-vb-net-for-a-property-defined-in-an-interface/2365193#2365193 – 2010-03-02 17:26:54

1

该语言目前不支持该语言,在Visual Basic 10中也不支持(即Visual Studio 2010版本)。有一个wishlist item for exactly this。在此之前,nobugz提出的解决方法是唯一的选择。

0

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

1

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

相关问题