【问题标题】:A class contains an array of objects. Do I need to set each of them to nothing on terminating the containing class?一个类包含一个对象数组。在终止包含类时,我是否需要将它们中的每一个都设置为空?
【发布时间】:2015-07-03 21:31:31
【问题描述】:

我正在使用类似下面的代码。通过循环 DB 结果并从每一行创建一个视图模型,在 Basket 类的范围内创建了一个 BasketItemViewModel 数组。

当我放弃 Basket 类并将其设置为空时,我是否需要遍历 BasketItemViewModel 的数组并将其中的每一个也设置为空?

Class Basket

    public GuidId
    public BasketItemViewModels
    public TotalItems
    public TotalCost

    Public Property Get TotalCostFormatted()
        TotalCostFormatted = FormatCurrency(TotalCost,0)
    End Property



    public Default function Init(p_GuidId, p_TotalItems, p_TotalCost)
        GuidId = p_GuidId
        BasketItemViewModels = GetBasketItemViewModels()
        TotalItems = p_TotalItems
        TotalCost = p_TotalCost
        set Init = Me
    end function 

    public function GetBasketItemViewModels()
        dim vmArray()

        for each row in dbResults
            // ...get some values...
            set vmArray(i) = (new BasketItemViewModel) (price, quantity, productId)
        next           

        GetBasketItemViewModels = vmArray
    end function 
End Class

【问题讨论】:

    标签: arrays vbscript asp-classic nothing


    【解决方案1】:

    不。这不是必需的。当您的 Basket 对象被销毁时,BasketItemViewModels 数组随之而来。当它发生时,该数组持有的所有引用都会被释放。

    考虑以下示例:

    Dim b
    Set b = New Basket
    Set b = Nothing
    WScript.Echo "After"
    
    Class Basket
        Public Eggs
        Sub Class_Initialize()
            Dim a(1)
            Set a(0) = New Egg
            Set a(1) = New Egg
            Eggs = a
        End Sub
    End Class
    
    Class Egg
        Sub Class_Terminate()
            WScript.Echo "Egg cracked."
        End Sub
    End Class
    

    这段代码产生的输出是:

    鸡蛋裂开。 鸡蛋裂开。 后

    Basket 对象被销毁时,证明Eggs 数组被清空,并且它的引用被释放。

    【讨论】:

    • 完美答案谢谢。和一个很好的例子来启动:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多