C#Getter/Setter问题 [英] C# Getter/Setter problem

查看:52
本文介绍了C#Getter/Setter问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在一个类中有一个属性:

Say i have a property in a class:

Vector3 position{get; set;}

所以我在某个地方创建了该类的实例,现在我想更改position.x,这现在是不可能的,因为getter和setter设置并获取了整个对象.所以我必须让一个临时Vector3更改其值,然后分配它.

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.

Vector3是一个结构,因此它是一个值类型

Vector3 is a struct so its a value type

推荐答案

IMO,在这里最简单的答案:

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;}
}

现在,如果只需要更改一个尺寸或更改obj.Position来更改所有内容,则可以更改obj.Xobj.Yobj.Z.

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.

如果需要名称position来实现接口,则应明确地进行操作:

If you need the name position to implement an interface, then do it explicitly:

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

这篇关于C#Getter/Setter问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆