首页 新闻 会员 周边

C# swap ref 的问题

0
悬赏园豆:10 [已解决问题] 解决于 2018-05-14 10:03
  

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不已经是引用类型了吗???

C#
sun_dust_shadow的主页 sun_dust_shadow | 初学一级 | 园豆:193
提问于:2018-05-12 16:53
< >
分享
最佳答案
1

不加ref的话,你只交换的是SwapRightListItem参数left、right的引用对象,而外面的aaa, bbb的引用对象并没有改变

收获园豆:10
jello chen | 大侠五级 |园豆:7306 | 2018-05-12 17:06

不明白,对引用对象而言,传的参并不会进行temp拷贝,也就是说外面的aaa bbb并没有拷贝进swap中吧?这个不是int等值类型啊?

sun_dust_shadow | 园豆:193 (初学一级) | 2018-05-12 17:08

@sun_dust_shadow: 画了个简单的图,大概是这样

jello chen | 园豆:7306 (大侠五级) | 2018-05-12 17:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册