以前接手老項目的時候有遇到一些的方法參數中使用了ref關鍵字加在傳參的參數前面的狀況。對於新手,這裏介紹和講解一下ref的用法和實際效果。spa
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 ; } } |
結果
.net
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" ; } } |
結果
orm
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; } } |
結果
對象