使用访问器公开类属性
我不知道描述我的问题的正确技术术语,所以我举一个例子:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可变结构是邪恶的另一个原因。一种解决方法是将维度公开为方便起见的访问器:
但除此之外;是的,您每次都需要执行
new Point(x,y)
,因为Point
是一个结构体。当您通过属性访问它时,您将获得它的一个副本,因此,如果您改变该副本,然后丢弃该副本,您就会丢失更改。Yet another reason that mutable structs are evil. One workaround is to expose the dimensions as accessors for convenience:
But other that this; yes you would need to do the
new Point(x,y)
each time, sincePoint
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.这里的问题是 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.