如果接口定义了ReadOnly属性,那么实现者如何将Setter提供给此属性?

tsi*_*lar 7 vb.net

对于接口的实现者,是否有一种方法ReadOnly可以定义属性以使其成为完整的读/写Property

想象一下,我定义了一个接口来提供一个ReadOnly Property(即,只是一个给定值的getter):

Interface SomeInterface

    'the interface only say that implementers must provide a value for reading
    ReadOnly Property PublicProperty As String

End Interface
Run Code Online (Sandbox Code Playgroud)

这意味着实施者必须承诺提供价值.但我希望给定的实现者也允许设置该值.在我的脑海中,这意味着提供Property的setter作为实现的一部分,做这样的事情:

Public Property PublicProperty As String Implements SomeInterface.PublicProperty
    Get
        Return _myProperty
    End Get
    Set(ByVal value As String)
        _myProperty = value
    End Set
End Property
Run Code Online (Sandbox Code Playgroud)

但这不会编译,因为对于VB编译器,实现者不再实现接口(因为它不再是ReadOnly).

从概念上讲,这应该可行,因为,最后,它只是意味着从接口实现getter,并添加一个setter方法.对于"正常方法",这没有问题.

有没有一种方法可以做到这一点,而不采用"接口隐藏"或"自制" SetProperty()方法,以及Property在实现中具有类似读/写属性的样式?

谢谢 !

--UPDATE-- (我把这个问题转移到一个单独的问题)我的问题是:"为什么不能在VB.NET中完成",当以下内容在C#.NET中有效时?":

interface IPublicProperty
{
    string PublicProperty { get; }
}
Run Code Online (Sandbox Code Playgroud)

实施:

public class Implementer:IPublicProperty
    {
        private string _publicProperty;

        public string PublicProperty
        {
            get
            {
                return _publicProperty;
            }
            set
            {
                _publicProperty = value;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

bde*_*eem 7

现在在Visual Studio 2015中受支持.

Visual Basic的新功能

只读接口属性

您可以使用readwrite属性实现只读接口属性.接口保证最小的功能,并且它不会阻止实现类允许设置属性.


tsi*_*lar 5

最后,我得到了一个符合我目标的解决方案:

  • 通过界面访问的用户至少会看到一个吸气剂
  • 访问该实现的用户可以读取和写入。

我这样做是“遮蔽”实现的属性,如下所示:

'users who access through interface see only the Read accessor
Public ReadOnly Property PublicProperty_SomeInterface As String Implements SomeInterface.PublicProperty
    Get
        Return _myProperty
    End Get
End Property


'users who work with the implementation have Read/Write access
Public Property PublicProperty_SomeInterface As String
    Get
        Return _myProperty
    End Get
    Set(ByVal value As String)
        _myProperty = value
    End Set
End Property
Run Code Online (Sandbox Code Playgroud)

然后,根据您的使用方式,您可以执行以下操作:

Dim implementorAsInterface As SomeInterface = New InterfaceImplementor()
logger.Log(implementor.PublicProperty) 'read access is always ok
implementor.PublicProperty = "toto" 'compile error : readOnly access

Dim implementor As InterfaceImplementor = New InterfaceImplementor()
implementor.PublicProperty = "toto" 'write access
Run Code Online (Sandbox Code Playgroud)