4

我不知道描述我的问题的正确技术术语,所以我举个例子:

    private Point _PrivateVect = new Point();
    public Point Publicvect
    {
        get
        {
            return _PrivateVect;
        }
        set
        {
            _PrivateVect = value;
        }
    }

问题是如果我想访问Publicvect.X我会得到错误Cannot modify the return value of 'Publicvect' because it is not a variable。有没有解决的办法?还是我只需要Publicvect = new Point(NewX, Publicvect.Y);永远做?

4

2 回答 2

2

可变结构是邪恶的另一个原因。一种解决方法是为方便起见将维度公开为访问器:

public Point PublicX {
    get {return _PrivateVect.X;}
    set {_PrivateVect.X = value;}
}
public Point PublicY {
    get {return _PrivateVect.Y;}
    set {_PrivateVect.Y = value;}
}

但除此之外;new Point(x,y)是的,您每次都需要这样做,因为Point它是一个结构。当您通过属性访问它时,您会获得它的副本,因此如果您改变副本然后丢弃副本,您只会丢失更改。

于 2010-07-31T07:19:19.457 回答
1

The problem you have here is that the Point type is a Value Type. So when you manipulate Pointvect.X you are really manipulating a temporary copy of the value type, which of course has no effect on the original instance.

于 2010-07-31T07:19:42.217 回答