当前位置: 移动技术网 > IT编程>开发语言>c# > C#中 ref 关键字的认识和理解

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

2020年01月18日  | 移动技术网IT编程  | 我要评论

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

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



值类型对象使用ref参数示例

 c# 控制台程序 值类型对象使用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
25
26
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关键字传参
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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; }
}

结果

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网