[英]Accessing properties of a property while using get set accessors
This may seem like a strange question, but here I go anyway. 这似乎是一个奇怪的问题,但是无论如何我还是要去。
I have a class called Sprite that has properties such as "Position" and "Size". 我有一个名为Sprite的类,它具有诸如“位置”和“大小”之类的属性。 When one of these properties are changed I need to fire a private method that changes the rectangle with the new position/size that is used in the Draw() method.
这些属性之一更改后,我需要触发一个私有方法,该方法将使用Draw()方法中使用的新位置/大小更改矩形。
So I thought I would use get set accessors so on the set I could set the private position varaible and then fire the event. 因此,我认为我会使用get set访问器,以便在set上设置私有位置变量,然后触发该事件。 Like this:
像这样:
private Vector3 position;
public Vector3 Position {
get { return this.position; }
set {
this.position = value;
this.SetDrawRectangle();
}
}
This works fine until I want to use one of Position's properties such as X, Y or Z. So if I was to do: 在我要使用Position的属性之一(例如X,Y或Z)之前,此方法可以正常工作。因此,如果要这样做:
sprite.Position.X = 10;
It won't work, the error I get is 它不起作用,我得到的错误是
Error 1 Cannot modify the return value of '.Sprite.Position' because it is not a variable.
错误1无法修改'.Sprite.Position'的返回值,因为它不是变量。
I would have to do this: 我将必须这样做:
sprite.Position = new Vector3(10, 0, 0);
But this would be awkward in some situations because you would have to keep passing the current Y and Z floats back in to the new Vector3. 但这在某些情况下会很尴尬,因为您必须不断传递当前的Y和Z浮动返回到新的Vector3中。
Has anyone got some help for a situation like this, or is what I'm trying to do just wrong and not possible. 有没有人在这种情况下获得过帮助,或者这是我正在尝试做的错误而不可能的事情。
Thanks in advance and I apologize for my ignorance! 在此先感谢您的无知!
When you execute this code 执行此代码时
sprite.Position.X = 10;
Sprite.Position
's setter will not be called. Sprite.Position
的setter将不会被调用。 It just calls the getter for Sprite.Position
and then the setter for Vector.X
which fails because Vector.X
seems read-only. 它只是呼吁吸气
Sprite.Position
,然后二传手Vector.X
因为它未能Vector.X
似乎只读。
So the answer is Yes if you can modify the code for Vector
class and No if you can't unless you want to use Reflection. 因此,如果可以修改
Vector
类的代码,则答案为“是”,如果不能修改则为“否”,除非您想使用Reflection。
您可以使用Vector3.Set方法。
Position.Set(10, 0, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.