使用访问器公开类属性

发布于 2024-09-12 05:47:30 字数 460 浏览 7 评论 0原文

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

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

问题是,如果我想访问 Publicvect.X 我收到错误 Cannot edit 'Publicvect' 的返回值,因为它不是变量。有办法解决这个问题吗?或者我只需要永远执行 Publicvect = new Point(NewX, Publicvect.Y);

I don't know the correct technical terms to describe my question, so I'll give an example:

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

The problem is that if I wanted to access Publicvect.X I get the error Cannot modify the return value of 'Publicvect' because it is not a variable. Is there a way around this? Or do I just need to do Publicvect = new Point(NewX, Publicvect.Y); forever?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伪心 2024-09-19 05:47:30

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

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是一个结构体。当您通过属性访问它时,您将获得它的一个副本,因此,如果您改变该副本,然后丢弃该副本,您就会丢失更改。

Yet another reason that mutable structs are evil. One workaround is to expose the dimensions as accessors for convenience:

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

But other that this; yes you would need to do the new Point(x,y) each time, since Point is a struct. When you access it via a property you get a copy of it, so if you mutate the copy and then discard the copy, you simply lose the change.

能否归途做我良人 2024-09-19 05:47:30

这里的问题是 Point 类型是值类型。因此,当您操作 Pointvect.X 时,您实际上是在操作值类型的临时副本,这当然对原始实例没有影响。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文