为什么下面的c#代码的结果还是abc

来源:百度知道 编辑:UC知道 时间:2024/06/04 18:58:29
using System;
using System.Collections.Generic;
using System.Text;

namespace AAAA
{
class BBBB
{
public static void Main(String[] args)
{
String s = "abc";
BBBB b = new BBBB();
b.get(s);
Console.WriteLine(s );
}

public void get(String s)
{
s = "aaaaaaaaaa";
}

}

}
请达人详细说明

自己看吧。 改成这样应该了解了吧
默认不加ref是值传递,在这里要传递引用,才可以改变对象,相同的变量,不同作用域,同时指向一个内存,只有用传递引用来改变。
因为作用域的问题,单独改变get函数里s的值拷贝,对Main自己的s没有作用。
还有个办法就是把s声明成类的属性,用值传递也可以做到。
就不多说了,共同学习。

using System;
using System.Collections.Generic;
using System.Text;

namespace AAAA
{
class BBBB
{
public static void Main(String[] args)
{
String s = "abc";
BBBB b = new BBBB();
b.get(ref s); Console.WriteLine(s);
Console.ReadKey();
}

public void get(ref string s)
{
s = "aaaaaaaaaa";
}

}

}

//再修改一下你的例子。看看get函数内部发生了什么,看输出就知道,get内部的s确实改变了,但Main里的还是不变,因为他们还是在各自的领域里起作用。……

using System;
using System.Collections.Generic;
using System.Text;

namespace AAAA
{
class BBBB