C#中 ref 關鍵字的認識和理解


C#中 ref 關鍵字的認識和理解

之前接手老項目的時候有遇到一些的方法參數中使用了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;
    }
}
結果 ![](https://img2018.cnblogs.com/blog/1060719/202001/1060719-20200117172410223-15416875.png)

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";
    }
}
結果 ![](https://img2018.cnblogs.com/blog/1060719/202001/1060719-20200117172410223-15416875.png)

類對象使用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; }
}

結果

作者: 啊蕭Styvn

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

版權:本站使用「CC BY 4.0」創作共享協議,轉載請在文章明顯位置注明作者及出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM