Private _Columns As ArrayList
Public Property Columns() As ArrayList
Get
Return _Columns
End Get
Set(Cols As ArrayList)
_Columns = Cols
End Set
Set(Cols As MyOwnList)
_Columns = New ArrayList
For Each o As MyObj in Cols
_Columns.Add(o.Column)
Next
End Set
End Property
这将允许我通过为其分配各种类型的集合来方便地设置属性...除了,我不能这样做,因为显然 Set 方法必须采用物业本身的类型......我得到了投诉:
'Set'参数必须与包含属性
具有相同的类型
有办法做到这一点吗?
答案 0 :(得分:3)
不,您无法更改自动属性中Setter所需参数的类型。
但是,您可以从示例中为MyOwnList提供自己的隐式转换函数,然后在将其传递给setter时会自动转换为ArrayList。
Class MyOwnList
' your class code here....
'
Public Shared Widening Operator CType(ByVal p1 As MyOwnList) As ArrayList
Dim columns As New ArrayList
For Each o As MyObj in p1
columns.Add(o.Column)
Next
return columns
End Operator
End Class
然后在你的程序的其他地方,这段代码可以工作:
Dim myList as new MyOwnList
SomeClass.Columns = myList
答案 1 :(得分:3)
它并没有真正超载,但以下内容可以提供(临时)解决方法:
Private Cols As ArrayList
Public Property Columns() As ArrayList
Get
Return _Columns
End Get
Set(Cols As ArrayList)
_Columns = Cols
End Set
End Property
Public WriteOnly Property SpecializedColumns() As MyOwnList
Set(value As MyOwnList)
Dim list As New ArrayList
For Each o As MyObj In value
list.Add(o.Column)
Next
Columns = list
End Set
End Property
我认为这与你可以获得真正的重载属性一样接近......
修改强>
我认为,正在尝试实现目标的正确方法是在ToArrayList()
课程中定义MyOwnList
方法。
Public Function ToArrayList()
Dim list As New ArrayList
For Each o As MyObj In Me.Items
list.Add(o.Column)
Next
Return list
End Function
并设置您的属性:
Columns = theMyOwnListObject.ToArrayList
如果您无法访问该类的源代码,您仍然可以通过扩展方法实现此目的。