首页 > 技术文章 > 【C#】传引用

OnlyACry 2020-09-12 10:09 原文

 1 using System;
 2 using System.Diagnostics;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 
 7 namespace cs_frist
 8 {
 9     class Program
10     {
11         static void Swap(ref int a, ref int b)
12         {
13             int t;
14             t = a; a = b; b = t;
15         }
16         static void AddStr(string str)
17         {
18             str += ".";
19             Console.WriteLine(str);
20         }
21         static void AddList(List<int> list)
22         {
23             list.Add(2);
24         }
25         static void Main(string[] args)
26         {
27             int a, b;
28             a = 1; b = 2;
29             Swap(ref a, ref b);
30             Console.WriteLine("a={0} b={1}", a, b);
31 
32             string str = "Hey";
33             AddStr(str);
34             Console.WriteLine(str); 
35             //更改string时也需要传引用而不是传值
36 
37             var list = new List<int> ();
38             list.Add(1);
39             AddList(list);
40             Console.WriteLine(list);
41             //List特别注意一下,传不传引用无所谓
42         }
43     }
44 }

 list是引用类型,而int , string , char等是基本类型,基本类型在需要交换或添加时需要“传引用”,而不是“传值”。

所以这里的string类型的变量str需要更改一下使用方法。

 1 static void AddStr(ref string str)
 2         {
 3             str += ".";
 4             Console.WriteLine(str);
 5         }
 6 //。。。略
 7 
 8 string str = "Hey";
 9             AddStr(ref str);
10             Console.WriteLine(str);

 

推荐阅读