我最近试图为一个Vector2字段创建一个属性,只是意识到它不能按预期工作.
public Vector2 Position { get; set; }
Run Code Online (Sandbox Code Playgroud)
这阻止我改变其成员的价值(X&Y)
查看有关此内容的信息,我读到为Vector2struct 创建属性只返回原始对象的副本而不是引用.
作为Java开发人员,这让我很困惑.
C#中的对象何时按值传递,何时通过引用传递?
是否所有struct对象都按值传递?
这些是来自ac#book的例子,我正在阅读这个例子实际上正在做的一点点麻烦,想要一个解释来帮助我进一步了解这里发生的事情.
//creates and initialzes firstArray
int[] firstArray = { 1, 2, 3 };
//Copy the reference in variable firstArray and assign it to firstarraycopy
int[] firstArrayCopy = firstArray;
Console.WriteLine("Test passing firstArray reference by value");
Console.Write("\nContents of firstArray " +
"Before calling FirstDouble:\n\t");
//display contents of firstArray with forloop using counter
for (int i = 0; i < firstArray.Length; i++)
Console.Write("{0} ", firstArray[i]);
//pass variable firstArray by value to FirstDouble
FirstDouble(firstArray);
Console.Write("\n\nContents of firstArray after " +
"calling FirstDouble\n\t");
//display contents …Run Code Online (Sandbox Code Playgroud)