我正在尝试开发一个简单的界面,允许从类生成快速列表。基本上,接口需要返回ID和名称。但是,某些类具有计算名称属性,该属性是只读的,其他类只使用读/写名称属性。基本上,我所关心的只是它有一个吸气剂,如果财产有一个二传手,那也没关系。如何编写此接口来处理或不抛出编译错误?
我看过this question并没有真正关注它,也许我只是密集了。如果是这样,请告诉我我的方式错误:)
答案 0 :(得分:5)
看起来其他问题的答案是有效的:这是一个示例:
Public Interface IReadOnly
ReadOnly Property Name() As String
End Interface
Public Interface IReadWrite
Inherits IReadOnly
Overloads Property Name() As String
End Interface
Public Class ReadOnlyClass
Implements IReadOnly
Private _Name
Public ReadOnly Property Name() As String Implements IReadOnly.Name
Get
Return _Name
End Get
End Property
End Class
Public Class ReadWriteClass
Implements IReadWrite
Private ReadOnly Property ReadOnly_Name() As String Implements IReadOnly.Name
Get
Return Name
End Get
End Property
Private _Name As String
Public Overloads Property Name() As String Implements IReadWrite.Name
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
End Class
上述方法实际上会导致实现IReadWrite的类也实现IReadOnly - 所以你实际上需要向下转换为IReadWrite才能设置属性。
另一种方法,它避免了这个问题,但在实现类和调用者中需要更多的逻辑,如下所示:
Public Interface ISometimesWritable
Property Name() As String
ReadOnly Property AllowNameEdit() As Boolean
End Interface
Public Class ReadOnlyClass
Implements ISometimesWritable
Public ReadOnly Property AllowNameEdit() As Boolean Implements ISometimesWritable.AllowNameEdit
Get
Return False
End Get
End Property
Private _Name As String
Public Property Name() As String Implements ISometimesWritable.Name
Get
Return _Name
End Get
Set(ByVal value As String)
Throw New NotSupportedException("Name cannot be set when AllowNameEdit is False")
End Set
End Property
End Class
Public Class ReadWriteClass
Implements ISometimesWritable
Public ReadOnly Property AllowNameEdit() As Boolean Implements ISometimesWritable.AllowNameEdit
Get
Return True
End Get
End Property
Private _Name As String
Public Property Name() As String Implements ISometimesWritable.Name
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
End Class
更新:回答关于向下转发的问题; “向下转换”是一个术语,用于描述将对象从超类,接口或抽象基类Type
转换为更具体的Type
。
例如,上面的第一个示例定义了两个接口:IReadOnly
和IReadWrite
。您会注意到IReadWrite
实现了IReadOnly
,这意味着您可以同时对IReadWrite
和 IReadOnly
调用实现{{1}的对象}}
由于IReadWrite
实现IReadWrite
,IReadOnly
被称为IReadWrite
的“子类”(尽管“子类”更准确地用于描述继承基类的类,而不是实现接口 - 为了简单起见,它们几乎是相同的概念)。如果IReadOnly
是IReadWrite
的子类,则反之亦然 - IReadOnly
是IReadOnly
的超类。< / p>
例如,我可以将IReadWrite
的实例描述为任一接口的实现:
ReadWriteClass