简体   繁体   中英

Accessing properties of a property while using get set accessors

This may seem like a strange question, but here I go anyway.

I have a class called Sprite that has properties such as "Position" and "Size". When one of these properties are changed I need to fire a private method that changes the rectangle with the new position/size that is used in the Draw() method.

So I thought I would use get set accessors so on the set I could set the private position varaible and then fire the event. Like this:

private Vector3 position;
public Vector3 Position { 
    get { return this.position; } 
    set {
        this.position = value;
        this.SetDrawRectangle();
    }
}

This works fine until I want to use one of Position's properties such as X, Y or Z. So if I was to do:

sprite.Position.X = 10;

It won't work, the error I get is

Error 1 Cannot modify the return value of '.Sprite.Position' because it is not a variable.

I would have to do this:

sprite.Position = new Vector3(10, 0, 0);

But this would be awkward in some situations because you would have to keep passing the current Y and Z floats back in to the new Vector3.

Has anyone got some help for a situation like this, or is what I'm trying to do just wrong and not possible.

Thanks in advance and I apologize for my ignorance!

When you execute this code

sprite.Position.X = 10;

Sprite.Position 's setter will not be called. It just calls the getter for Sprite.Position and then the setter for Vector.X which fails because Vector.X seems read-only.

So the answer is Yes if you can modify the code for Vector class and No if you can't unless you want to use Reflection.

您可以使用Vector3.Set方法。

Position.Set(10, 0, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM