开发者

C# Getter/Setter problem

Say i have a property in a cl开发者_如何学Cass:

Vector3 position{get; set;}

So i create an instance of that class somewhere and now i want to change position.x, that would be impossible now because the getter and setter set and get the whole object. So i have to make a temporary Vector3 change its values and then assign it.

Normally i would make position a public field so that problem would be solved. But i cant do it in this case because position is an implementation of an interface and interfaces cant have fields.

So how can i solve this the best way.

Edit: Vector3 is a struct so its a value type


Is the straightforward solution somehow not acceptable?

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

What's wrong with that? It seems perfectly straightforward.


IMO, the easiest answer here:

private Vector3 position;
public Vector3 Position {
    get {return position;}
    set {position = value;} // with @Mehrdad's 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 an interface, then do it explicitly:

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


That's one of the issues with mutable value types. You can create a new instance of the value type with the new X value and reassign in to the property. You can make the instance creation easier by providing useful constructors or adding methods that return a modified object (instead of modifying the value).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜