【发布时间】:2011-06-10 13:55:44
【问题描述】:
接口的实现者有没有办法定义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
这意味着实施者必须承诺提供价值。但我希望给定的实施者也允许设置该值。在我看来,这意味着提供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
但这不会编译,因为对于 VB 编译器,实现者不再实现接口(因为它不再是 ReadOnly)。
从概念上讲,这应该可行,因为最后,它只是意味着从接口实现 getter,并添加一个 setter 方法。对于“普通方法”来说,这是没有问题的。
有没有办法做到这一点,而不诉诸“界面隐藏”或“自制”SetProperty() 方法,并且具有Property 的样式在实现中表现得像读/写属性?
谢谢!
--更新-- (我已将这个问题 to a separate Question 移动) 我的问题真的是:“为什么不能在 VB.NET 中完成”,当以下内容在 C#.NET 中有效时?”:
interface IPublicProperty
{
string PublicProperty { get; }
}
实施:
public class Implementer:IPublicProperty
{
private string _publicProperty;
public string PublicProperty
{
get
{
return _publicProperty;
}
set
{
_publicProperty = value;
}
}
}
【问题讨论】:
-
更新是个好问题,但我无法回答,我更喜欢 c# 实现。
-
我想我会在一个单独的问题中发布它。还是谢谢!
标签: vb.net