2

好的,也许这不是一种方法。这就是我想做的事情:

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”参数必须与包含属性具有相同的类型

有没有办法做到这一点?

4

2 回答 2

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
于 2012-05-12T05:33:43.440 回答
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

如果您无权访问该类的源代码,您仍然可以通过扩展方法来实现这一点。

于 2012-05-12T08:32:37.297 回答