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

When inverting Vector3 value compiler complains about Syntax

今天我在与向量作斗争,我对此有疑问。我必须反转 Y 向量值,但每次编译时,编译器都会抱怨:

Syntax error ',' expected

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

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

编译器是正确的。

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

所以下面两个都可以:

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