值传递与引用传递

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)
{
 //...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值