1先看看下面的表
Parameter Modifier Meaning in Life
(none) If a parameter is not marked with a parameter modifier, it is assumed to
be passed by value, meaning the called method receives a copy of the
original data.
out Output parameters are assigned by the method being called (and therefore
passed by reference). If the called method fails to assign output parameters,
you are issued a compiler error.
params This parameter modifier allows you to send in a variable number of
identically typed arguments as a single logical parameter. A method can
have only a single params modifier, and it must be the final parameter of
the method.
ref The value is initially assigned by the caller, and may be optionally reassigned
by the called method (as the data is also passed by reference). No compiler
error is generated if the called method fails to assign a ref parameter.
上面归纳了几种修饰符的区别
值传递是传递的一个拷贝(一个副本)如果改变副本的值,并不影响原来值。
而引用传递就会改变原来的值。
让我们看看下面的例子 以值类型的方式传递引用类型 看什么可以改变
class Person
{
public string fullName;
public byte age;
public Person(string n, byte a)
{
fullName = n;
age = a;
}
public Person(){}
public void PrintInfo()
{
Console.WriteLine("{0} is {1} years old", fullName, age); }
}
public static void SendAPersonByValue(Person p)
{
// Change the age of 'p'?
p.age = 99;
// Will the caller see this reassignment?
p = new Person("Nikki", 999);
}
static void Main(string[] args)
{
// Passing ref-types by value.
Console.WriteLine("***** Passing Person object by value *****");
Person fred = new Person("Fred", 12);
Console.WriteLine("Before by value call, Person is:");
fred.PrintInfo();
SendAPersonByValue(fred);
Console.WriteLine("After by value call, Person is:");
fred.PrintInfo();
}
age的值变了 但fred所指的的object并没有变化
如果我们想让它所指的object变化 只要引用ref就可以了
SendAPersonByReference(ref mel);
public static void SendAPersonByReference(ref Person p)
{
//...
}