如何设置属性的成员?

Tho*_*mas 0 c# xna

我有一个像这样的矢量的属性

    public Vector2 TestVector
    {
        get { return testvector; }

        set
        {
            testvector = value;

        }
    }
Run Code Online (Sandbox Code Playgroud)

Vector2有成员X和Y.

当我想将property.x和property.y设置为值时,它不起作用

// this does not work
TestVector.X = 10;
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

编辑:我看到我得到的答案说它是一个结构,但实际上我有一个名为dVector2的组合类,它是一个类类型而不是结构,我使用它.为了简单起见,我只把vector2放在这里,但这种情况适得其反.

Jon*_*art 5

Vector2是一个结构(值类型).所以这是你尝试时发生的事情TestVector.X = 10:

{
    Vector2 temp = get_TestVector();   // copy is made during return from
                                       // hidden call to property getter method

    temp.X = 10;                       // modifying the copy

                                       // copy is gone
}
Run Code Online (Sandbox Code Playgroud)

最终结果是没有任何反应.

不幸的解决方案是:

TestVector = new Vector2 { X = 10, Y = TestVector.Y };
Run Code Online (Sandbox Code Playgroud)

另一种可能适用于您的情况的解决方案是简单地创建TestVector一个公共字段,而不是属性:

public Vector2 TestVector;
Run Code Online (Sandbox Code Playgroud)