myObject.rect.X = 100
myObject has a property called rect (which is a Rectangle). During runtime I will want to chage the X position of such rectangle, but I am given this error:
Expression is a value and therefore cannot be the target of an ass开发者_开发百科ignment.
Then, how am I supposed to change such values?
I assume you are talking about System.Drawing.Rectangle
here. Rectangle
is a value type (Structure
in VB.NET), so when you access it via the myObject.rect
property, you get a copy of it locally. Since you have a copy of the values instead of a reference to the instance, you cannot update it.
If you want to change myObject
's Rectangle
property, you can update myObject
to refer to a newly constructed Rectangle
with values you desire. For example:
Dim myObject As MyObject = New MyObject()
' Prints 0
Console.WriteLine(myObject.rect.X)
' Refer to a new rectangle with X=100 and all other values kept the same
myObject.rect = New Rectangle(
100,
myObject.rect.Y,
myObject.rect.Width,
myObject.rect.Height
)
' Prints 100
Console.WriteLine(myObject.rect.X)
精彩评论