C#若不加限制传值时自带的类型为值传递,自创的类型为引用传递
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class AA { string s; } class Program { static void change(string s) { s = "000"; } static void Main(string[] args) { string s = "123"; change(s); Console.WriteLine(s); } } }
输出 123
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class AA { public string s; public AA() { s = "123"; } } class Program { static void change(AA t) { t.s = "000"; } static void Main(string[] args) { AA t = new AA(); Console.WriteLine(t.s); change(t); Console.WriteLine(t.s); } } }
输出
123
000
可以指定为ref/out传值(函数声明和函数调用时都要加这个关键字)
其区别:
ref必须要在调用前初始化,out必须在函数内初始化(不初始化前函数内不能使用)