Problem with C # Getter / Setter

Let's say I have a property in the class:

Vector3 position{get; set;} 

So, I am creating an instance of this class somewhere, and now I want to change position.x, this would not be possible now, because the getter and setter installed and received the whole object. So I need to make a temporary Vector3 change its values ​​and then assign it.

Usually I would take the position of a public field so that the problem is resolved. But I cannot do this in this case, because the position is the implementation of the interface, and the interfaces cannot have fields.

So how can I solve this in the best way.

Edit: Vector3 is a structure, so its value type

+3
source share
4 answers

IMO, the easiest answer is here:

 private Vector3 position; public Vector3 Position { get {return position;} set {position = value;} // with @Mehrdad optimisation } public float X { get {return position.X;} set {position.X = value;} } public float Y { get {return position.Y;} set {position.Y = value;} } public float Z { get {return position.Z;} set {position.Z = value;} } 

Now you can change obj.X , obj.Y and obj.Z if you only need to change one dimension or change obj.Position to change everything.

If you need the name position to implement the interface, do this explicitly:

 Vector3 IWhateverInterface.position { get {return position;} set {position = value;} } 
+5
source

Is a direct solution somehow unacceptable?

 foo.position = new Vector(newX, foo.position.Y, foo.position.Z); 

What is wrong with that? It seems quite simple.

+9
source

This is one of the problems with variable value types. You can create a new instance of the value type with a new X value and reassign it. You can simplify instantiation by providing useful constructors or by adding methods that return a modified object (instead of changing the value).

+2
source

Pre-PS : it's too late to know that Vector3 is a value type; so the next post will not be very useful. Sorry for this mistake.

Well, although interfaces cannot have fields, they can have properties, for example:

 interface IVector3 { double X { get; set; } double Y { get; set; } double Z { get; set; } } 

In your Vector3 you simply implement things like everything else:

 class Vector3 : IVector3 { double IVector3.X { get { ... } set { ... } } ... } 

Now back to your position property. You bind the property to a fixed instance during initialization and provide only the recipient:

 Vector3 position { get { return _position; } } private Vector3 _position = new Vector3(...); 

By making the read-only property (i.e. no setter), you are sure that it will not be replaced by a new Vector3 object. Instead, you bind it to a fixed instance ( _position ) during initialization. But you can change Vector3 by assigning new values ​​to position.X , position.Y or position.Z .

0
source

Source: https://habr.com/ru/post/1302362/


All Articles