值参数与引用参数(C#)

C#参数默认是传值的。

如果参数是值类型,那么调用方法获得的实参是值的副本,这样在被调用的方法中更改实参值怎么也影响不到调用者

的原始变值。

而如果参数是Ref引用类型,那么实参是有ref前缀的变量(不是值),这种情况下对其进行重新赋值就更改了原始变量

值(更改了引用[地址]所指向的数据)。

概括的说,我们能更改带有ref前缀的变量的原始值,不带ref前缀的变量更改不了原始值。

下面是一个例子:

public ValueRefExample()
{
    this.InitializeComponent();

    string first = "漩涡";
    string second = "鸣人";

    txblk1.Text = string.Format("初始值:First:{0},Second:{1}", first, second);

    Swap(first, second);
    txblk2.Text = string.Format("传值方式交换值:First:{0},Second:{1}", first, second);

    Swap(ref first, ref second);
    txblk3.Text = string.Format("传引用方式交换值:First:{0},Second:{1}", first, second);

    string s1 = "宇智波";
    string s2 = "佐助";
    
    txblk4.Text = string.Format("初始值:S1:{0},S2:{1}", s1, s2);

    Swap(ref s1, s2);
    txblk5.Text = string.Format("传值传引用混合方式交换值:S1:{0},S2:{1}", s1, s2);
}

//传值方式传递变量
static void Swap(string str1,string str2)
{
    string temp = str1;
    str1 = str2;
    str2 = temp;
}

//传引用方式传递变量
static void Swap(ref string str1, ref string str2)
{
    string temp = str1;
    str1 = str2;
    str2 = temp;
}

//传值传引用混合传递变量
static void Swap(ref string str1,string str2)
{
    string temp = str1;
    str1 = str2;
    str2 = temp;
}

结果截图:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值