开发者

How to reference "Automatic" Properties in my class?

The tutorial I'm following (http://www.bluerosegames.com/xna101/post/Lesson-9-Improving-the-BouncingBall-Class-Using-Properties.aspx)

private Vector2 _position;
public Vector2 Position
{
    get

    {
        return _position;
    }
    set
    {
        _position = value;
    }
}

does not use the automatic properties feature in the code. I'd like to skip most of the typing using the automatic properties but I have problems later on in the code. I've commented the lines below that are affected.

public Vector2 Position { get; set; }

    public void Update()
    {
        Position = Position + Velocity;

        if (Position.X < 0 || Position.X 开发者_JAVA百科> GraphicsViewport.Width - Texture.Width)
        {
            // If we get in here, we've hit a vertical wall
            Velocity.X = -Velocity.X; // doesn't work
            Position.X = Position.X + Velocity.X; // doesn't work
        }
        if (Position.Y < 0 || Position.Y > GraphicsViewport.Height - Texture.Height)
        {
            // If we get in here, we've hit a horizontal wall
            Velocity.Y = -Velocity.Y; // doesn't work
            Position.Y = Position.Y + Velocity.Y; // doesn't work
        } 
    }

The error that I get in Visual Studio states that "Cannot modify the return value of WindowsGame1.BouncingBall.Position' because it is not a variable." So how can I get the code to work with the automatic properties?

Thank you! John


Your exact question has already been asked and answered:

This code isn't trying to do what you think it's trying to do...

Vector2 is a struct, so your call in Update first copies Position onto the stack, adds velocity.X to the new Vector2's 'X' and then throws it away. The original value was never modified.

The C# compiler catches your mistake in this case (phew!). You instead need to do:

Position = new Vector2(Position.X+velocity.X, Position.Y);

The difference between value and reference types is fundamental in C# - the C# specification describes that difference immediately after "hello, world"

See section 8.2 of the C# specification for more information:

http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf

Alun Harford

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜