猿问

C# swap ref 的问题

  

public class DicTestClass
{
public DicTestClass(int a)
{
mAA = a;
}
public int mAA = 0;

}

public static void SwapRightListItem(ref DicTestClass left, ref DicTestClass right)
{
DicTestClass temp = null;
temp = right;
right = left;
left = temp;
}


static void Main(string[] args)
{
DicTestClass aaa = new DicTestClass(1);
DicTestClass bbb = new DicTestClass(2);

SwapRightListItem(ref aaa, ref bbb);

Console.WriteLine(" aaa:" + aaa.mAA);
Console.WriteLine(" bbb:" + bbb.mAA);

}

上面的代码:输出值是2,1   如果全去掉ref  输出值是1,2   

为什么?   class不已经是引用类型了吗???

慕工程0101907
浏览 722回答 1
1回答

小唯快跑啊

不加ref的话,你只交换的是SwapRightListItem参数left、right的引用对象,而外面的aaa, bbb的引用对象并没有改变
随时随地看视频慕课网APP
我要回答