- “值传递”和“引用传递”的区别2007年03月07日 星期三 09:25______________________________________________________________________________________________
答1:
举个例子。
假设a=b为值传递,改变a的值,b不会改变。
如果为引用传递,则a是b的镜象,改变a,也会改变b
______________________________________________________________________________________________
答2:
能举个小程序例子吗?非常感谢
______________________________________________________________________________________________
答3:
小例子来了:
using System;- namespace LostinetSample
{
public class PointClass
{
public int x;
public int y;
}
public struct PointStruct
{
public int x;
public int y;
} - class Class1
{
[STAThread]
static void Main(string[] args)
{
PointClass pc=new PointClass();
pc.x=10;
pc.y=10;
Change(pc); //传递引用,其引用的操作能反映过来:
Console.WriteLine("pc.x"+pc.x);
Console.WriteLine("pc.y"+pc.y);
PointStruct ps=new PointStruct();
ps.x=10;
ps.y=10;
Change(ps); //传递副本,其副本的操作不影响原来的对象
Console.WriteLine("ps.x"+ps.x);
Console.WriteLine("ps.y"+ps.y);
}
static void Change(PointClass o)
{
o.x=100;
o.y=100;
}
static void Change(PointStruct o)
{
o.x=100;
o.y=100;
}
}
}- ______________________________________________________________________________________________
答4:
c#里面一般来说int型的直接赋值都使值传递的。除非加上 ref,
for example: ref a=b;
这就表示值引用。
但c#里面凡是对象间的拷贝都使基于引用方式的。
上面我已经讲过两者的区别了,相信你应该明白了。