C# · 12月 24, 2021


出于某种原因,(我是C#的新手并且知道 java和c)当我想要传递值时,C#会继续复制对象.我有一个Vector2类的arraylist,每当我想增加一个值时,我必须这样做: Vector2 d = (Vector2) myObjects[i];d.Y++;myObjects [i] = d;


Vector2 d = (Vector2) myObjects[i];d.Y++;


解决方法 在C#中,类的实例作为引用传递,而结构的实例通过复制传递(默认情况下).


A class is a reference type. When an object of the class is created,the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable,the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.

A struct is a value type. When a struct is created,the variable to which the struct is assigned holds the struct’s actual data. When the struct is assigned to a new variable,it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.