C#按值传递对象?

前端之家收集整理的这篇文章主要介绍了C#按值传递对象?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
出于某种原因,(我是C#的新手并且知道 java和c)当我想要传递值时,C#会继续复制对象.我有一个Vector2类的arraylist,每当我想增加一个值时,我必须这样做:
Vector2 d = (Vector2) myObjects[i];
d.Y++;
myObjects [i] = d;

我希望能够这样做:

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

并完成.我在网上搜索,令人惊讶的是没有答案.
顺便说一句,矢量是一个结构.

解决方法

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

答案就在那里应该是:http://msdn.microsoft.com/en-us/library/vstudio/ms173109.aspx

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.

原文链接:/csharp/92036.html

猜你在找的C#相关文章