加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#按值传递对象?

发布时间:2020-12-15 04:20:08 所属栏目:百科 来源:网络整理
导读:出于某种原因,(我是C#的新手并且知道 java和c)当我想要传递值时,C#会继续复制对象.我有一个Vector2类的arraylist,每当我想增加一个值时,我必须这样做: Vector2 d = (Vector2) myObjects[i];d.Y++;myObjects [i] = d; 我希望能够这样做: Vector2 d = (Vecto
出于某种原因,(我是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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读