VB中List(Of Object)的扩展方法

时间:2014-02-02 03:03:56

标签: vb.net list methods

我有一个扩展方法,可以很好地将对象转换为我的表单对象。

'Copy an object to a form object
<Extension()> _
Public Function FromModel(ToObject As BaseFormObject, ByRef FromObject As Object) As Boolean

    ToObject = FromObject

    Return True
End Function

我想为对象列表做同样的事情。

'Copy a list of objects to form objects
<Extension()> _
Public Function FromModelList(ToList As List(Of BaseFormObject), ByRef FromList As List(Of Object)) As Boolean

    For Each FromItem As Object In FromList
        'Create a new BaseFormObject for every item in FromList, Add it to our From List
        Dim newFormObject = New BaseFormObject()
        newFormObject.FromModel(FromItem)
        ToList.Add(newFormObject)
    Next

    Return True
End Function

创建新的List(Of BaseFormObject)不允许我访问方法“FromModelList”。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您的代码运行正常。

我创建了这段代码:

    Dim lst As New List(Of BaseFormObject)

当我输入lst.

时,我获得了扩展成员

我将在这里发表意见,并建议你实际上并没有实例化List(Of BaseFormObject),而是List(Of ActualFormObject)之类的地方ActualFormObject继承BaseFormObject }}

所以如果我使用这段代码:

    Dim lst As New List(Of ActualFormObject)

然后你没有得到扩展成员。如果这是你所希望的,那么很容易解决。

将您的代码更改为:

<Extension()> _
Public Function FromModelList(Of T As {New, BaseFormObject})(ToList As List(Of T), ByRef FromList As List(Of Object)) As Boolean
    For Each FromItem As Object In FromList
        'Create a new BaseFormObject for every item in FromList, Add it to our From List
        Dim newFormObject = New T()
        newFormObject.FromModel(FromItem)
        ToList.Add(newFormObject)
    Next
    Return True
End Function

然后在子类列表上获得扩展成员。