之前接手老專案的時候有遇到一些的方法引數中使用了ref關鍵字加在傳參的引數前面的情況,對于新手,這里介紹和講解一下ref的用法和實際效果,
- CLR中默認所有方法的引數傳遞方式都是傳值,也就是說不管你傳遞的物件是值型別還是參考型別,在作為引數傳入到方法中時,傳遞的是原物件的副本,無論在方法中對該物件做何更改,都不影響外部的物件,
- 而使用了ref引數之后,傳遞的是物件的參考
- 對于值型別,傳遞的是值的參考,可以理解為值的地址
- 對于參考型別,傳遞的就是變數的參考,同樣可以理解成變數的堆疊地址
值型別物件使用ref引數示例
C# 控制臺程式 值型別物件使用ref引數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關鍵字傳參|
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關鍵字傳參|
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; } } |
結果

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/77376.html
標籤:C#
