C# 传递参数(值或引用)? [英] C# passing parameter (value or reference)?

查看:56
本文介绍了C# 传递参数(值或引用)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我,当你将一个对象传递给一个方法时,它是按值"传递的.我做了一个小测试来检查它:

I've been told that when you pass an Object to a method, it's passed "by value". I made a little test to examine it:

Point p = new Point(1, 1);
Circle c = new Circle(p);
p.x = 999;
Console.WriteLine(c.p.x);

上面的代码打印999",但我认为对象被复制到方法
有人告诉我,如果您不使用ref"(或out"),则该方法会获取值
的对象.

the code above prints "999", but I thought the object is copied to the method
I've been told that if you're not using "ref" (or "out") the method get the value
of the object.

有人可以给我说清楚吗?
谢谢,
袜套

can someone make it clear to me?
thanks,
socksocket

推荐答案

假设 Point 被声明为类,而不是 p 本身被复制,referencep 被复制.所以它仍然是按值传递的.您传递引用的值.

Assuming Point is declared as class, not p itself is copied, the reference to p is copied. So it's still pass by value. You pass the value of a reference.

当说Point p = new Point(1, 1);(如果point是一个引用类型),人们可能会认为它是一个包含Point的变量,但实际上它是一个变量,其中包含对存储在其他地方的 Point 的引用.

When saying Point p = new Point(1, 1); (and if point is a reference type), one might think it is a variable containing a Point, but in fact it is a variable containing a reference to a Point that is stored somewhere else.

这篇关于C# 传递参数(值或引用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆