我正在用C#编写Unity3D的脚本,并在我的一个名为constraintForType
的类中有一个小帮助器方法,它返回某个类型的公共字段,如下所示:
public Constraint topConstraint = Constraint.falseConstraint;
public Constraint bottomConstraint = Constraint.falseConstraint;
enum ConstraintType {
Top,
Bottom
}
Constraint constraintForType(ConstraintType type) {
switch(type) {
case ConstraintType.Top:
return topConstraint;
case ConstraintType.Bottom:
return bottomConstraint;
}
return Constraint.falseConstraint;
}
我从Update
循环调用此方法,但似乎我返回的约束与公共声明(可能是副本?)不同。
所以在Update
循环中,这将起作用:
void Update() {
topConstraint.constant = // Calculated value
}
但这不是:
void Update() {
Constraint con = constraintForType(ConstraintType.Top);
con.constant = // Calculated value
}
我想也许这个方法正在返回公共字段的副本,所以我将其更改为:
void constraintForType(ConstraintType type, ref Constraint con) {
switch(type) {
case ConstraintType.Top:
con = topConstraint;
break;
case ConstraintType.Bottom:
con = bottomConstraint;
break;
}
}
所以我在Update
:
Constraint con = Constraint.falseConstraint;
constraintForType(ConstraintType.Top, ref con);
但这仍然不起作用。
这里发生了什么?
编辑:
Constraint
是一个结构。
答案 0 :(得分:1)
将Constraint -struct更改为class。结构是(通常)不可变的值类型。
答案 1 :(得分:1)
你是对的,你的第一种方法是返回一份stuct。但是,您的第二个版本也在制作副本:
void constraintForType(ConstraintType type, ref Constraint con) {
switch(type) {
case ConstraintType.Top:
con = topConstraint; // struct is copied here
break;
case ConstraintType.Bottom:
con = bottomConstraint; // struct is copied here
break;
}
}
在你的情况下使这项工作的一种方法是在辅助函数内部分配
void constraintForType(ConstraintType type, Foo constant) {
switch(type) {
case ConstraintType.Top:
topConstraint.constant = constant;
break;
case ConstraintType.Bottom:
bottomConstraint.constant = constant;
break;
}
}
当然,如果您没有特别的理由使用可变结构,请改用类。 Mutable structs have some difficulties.