当反转Vector3值时,编译器会抱怨语法

时间:2015-06-01 21:15:03

标签: c# vector syntax-error expected-exception

今天我正在努力与矢量,我有这个问题。我必须反转Y向量值,但每次编译时,编译器都抱怨:

  

语法错误','预期

 vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f) {
   Y = -vector.Y;  //error shows here at the semicolon
 }; 

1 个答案:

答案 0 :(得分:2)

您正在使用对象初始化程序语法。

编译器是正确的。

如果要初始化多个属性,则可以在其中放置逗号而不是分号。即使在最后一个属性被初始化之后,逗号也是合法的,但是分号是不合法的。

所以以下两个中的任何一个都可以:

vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f) {
   Y = vector.Y
 }; 

vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f) {
   Y = vector.Y,
 }; 

话虽如此,这只会满足编译器。 你真正想做什么

请注意,在您阅读vector.Y时,vector变量尚未获得新值,因此您正在读取旧值。

基本上,代码是这样做的:

var temp = = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), (float) ((-512 + ((iD / 8) * 0x40)) + 0x20), -200f);
temp.Y = vector.Y;
vector = temp;

为什么不简单地通过构造函数分配它?

vector = new Vector3((float) ((-256 + ((iD & 7) * 0x40)) + 0x20), vector.Y, -200f);