static void Main()
{
string a = "test is a ";
test(a);
Console.WriteLine("call after : {0} ",a);
Console.ReadKey();
}
static void test(string a)
{
a = "fun call ";
}
}
运行结果还是“test is a”,没有改变传入参数。
尽管string属于引用类型,它在参数传递时表现出了按值传递的特色。
static void Main()
{
person li = new person("li", 15);
person.test(li);
Console.WriteLine("{0} {1}",li.pname,li.page);
Console.ReadKey();
}
}
class person
{
public int page;
public string pname;
public person(string name,int age)
{
pname = name;
page = age;
}
public static void test(person p)
{
p.pname = "wang";
p.page = 20;
p = new person("zhao", 30);
}
}
运行结果,改成了wang和20,虽然是按值传递,但还是改变了传入参数。
不过p = new person(“zhao”, 30); 这一行代码被忽略,不能改变所引用的对象。
如果把test(person p)修改成test(ref person p),那么结果会变成zhao,30,连引用的对象都改变了。