开发者

For each variable acting like a local var?

I stumbled upon something i don't quite see the logic of. Let's ork with following piece of code:

For Each ds As DerivedScale In List
    If ds.ScaleID = scaleId Then
        ds.ScaleID = ds.ScaleID + scaleStep
        CType(Li开发者_StackOverflow中文版st(myCounter + scaleStep), DerivedScale).ScaleID = scaleId
        myDerivedScale = ds
        ds = List(myCounter + scaleStep)          <---------------------
        List(myCounter + scaleStep) = myDerivedScale
        Exit For
    End If
    myCounter += 1
Next

This piece is written for 2 records to change place and change the sequence number (scaleid). The arrow indicates where the issue occurs. The item "ds" is replaced by the object 1 indexnumber higher/lower. This does however not effect that object in the List. So when i check, item ds isn't set.

However, when i look at ds.ScaleId = ds.ScaleID + scaleStep, this is reflected in the List.

So what I am wondering is: is "ds" acting like a local variable here, and can i only make changes to it's properties?

Thanks in advance.


ds is a reference to an object that is also referenced by the list. So when you set properties on it, those changes are reflected in the list as well. But since ds is just reference, as you surmise, changing what it refers to will not affect the list.


You need to iterate through the list by index instead of by the enumerator (all you're getting is a reference here). Then you can swap the objects by index and change their properties.


Objects in .Net are passed by reference.

You have a single DerivedScale instance in your list; the For Each loop iterates over the same instances that are in the list.
No copies are made; you're modifying the objects themselves.


That variable is scoped to the loop in which it is declared. Reassigning ds will not alter the list because both ds and the list have an object reference to some item, you are merely changing which item ds refers to without affecting the list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜