C#中 ref 关键字的认识和理解

之前接手老项目的时候有遇到一些的方法参数中使用了ref关键字加在传参的参数前面的情况。对于新手,这里介绍和讲解一下ref的用法和实际效果。

CLR中默认所有方法的参数python基础教程
传递方式都是传值,也就是说不管你传递的对象是值类型还是引用类型,在作为参数传入到方法中时,传递的是原对象的副本。无论在方法中对该对象做何更改,都不影响外部的对象。
而使用了ref参数之后,传递的是对象的引用
对于值类型,传递的是值的引用,可以理解为值的地址
对于引用类型,传递的就是变量c#教程的引用,同样可以理解成变量的栈地址

值类型对象使用ref参数示例
C# 控制台程序 值类型对象使用ref参数

class Program
{
    static void Main(string[] args)
    {
        int testInt = 10;
        Console.WriteLine(testInt);

        DoRef(ref testInt);
        Console.WriteLine(testInt);

        DoNotRef(testInt);
        Console.WriteLine(testInt);

        Console.ReadLine();

    }

    public static void DoRef(ref int txt)
    {
        txt = 10000000;
    }
    public static void DoNotRef(int txt)
    {
        txt = 55555555;
    }
}

结果
string类型对象使用ref参数示例
C# 控制台程序 String类型对象使用ref关键字传参
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Program
{
static void Main(string[] args)
{
string testValue = “origin”;
Console.WriteLine(testValue);

    UseRef(ref testValue);
    Console.WriteLine(testValue);

    NotUseRef(testValue);
    Console.WriteLine(testValue);

    Console.ReadLine();
}
public static void UseRef(ref string txt)
{
    txt = "ref txt";
}
public static void NotUseRef(string txt)
{
    txt = "not ref txt";
}

}
结果
类对象使用ref传参示例
C# Code 控制台程序 类对象使用ref关键字传参

class Program
{
    static void Main(string[] args)
    {
        TestModel t0 = new TestModel()
        {
            Text = "test"
        };

        Console.WriteLine(t0.Text);

        UseRef(ref t0);
        Console.WriteLine(t0.Text);

        NotUseRef(t0);
        Console.WriteLine(t0.Text);

        Console.ReadLine();
    }
    public static void UseRef(ref TestModel tModel)
    {
        tModel.Text = "use ref";
    }
    public static void NotUseRef(TestModel tModel)
    {
        tModel.Text = "not use ref";
    }
}

public class TestModel
{
    public string Text { get; set; }
}

结果

作者: 啊萧Styvn

出处:https://www.cnblogs.com/Joick/p/12206715.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值