看看下面别人发过的你就明白了 using System.Collections.Generic; using System.Text; using System; namespace ConsoleApplication1 { class Value { public int i = 15; } class Program { static void Main(string[] args) { Program t = new Program(); t.first(); } public void first() { int i = 5; Value v = new Value(); v.i = 25; second(v, i); Console.WriteLine(v.i);//20 } public void second(Value v, int i) { i = 0; v.i = 20; Value val = new Value(); v = val;//此处t被指向了val的地址,和原先的v断开了联系 Console.WriteLine(v.i + " " + i + " ");//15,0 } } } 15 0 20 using System.Collections.Generic; using System.Text; using System; namespace ConsoleApplication1 { class Value { public int i = 15; } class Program { static void Main(string[] args) { Program t = new Program(); t.first(); } public void first() { int i = 5; Value v = new Value(); 此时v.i=15,i=5 v.i = 25; second(ref v, i); Console.WriteLine(v.i);//20 } public void second(ref Value v, int i) { i = 0; v.i = 20; Value val = new Value(); v = val; Console.WriteLine(v.i + " " + i + " ");//15,0 } } } 15 0 15
不加out和ref,你可以修改这个对象的属性
加了out和ref,你可以使这个变量指向一个新的对象~
using System.Collections.Generic;
using System.Text;
using System; namespace ConsoleApplication1
{
class Value
{
public int i = 15;
}
class Program
{
static void Main(string[] args)
{
Program t = new Program();
t.first();
}
public void first()
{
int i = 5;
Value v = new Value();
v.i = 25;
second(v, i);
Console.WriteLine(v.i);//20
}
public void second(Value v, int i)
{
i = 0;
v.i = 20;
Value val = new Value();
v = val;//此处t被指向了val的地址,和原先的v断开了联系
Console.WriteLine(v.i + " " + i + " ");//15,0
}
}
}
15 0
20
using System.Collections.Generic;
using System.Text;
using System; namespace ConsoleApplication1
{
class Value
{
public int i = 15;
}
class Program
{
static void Main(string[] args)
{
Program t = new Program();
t.first();
}
public void first()
{
int i = 5;
Value v = new Value(); 此时v.i=15,i=5
v.i = 25;
second(ref v, i);
Console.WriteLine(v.i);//20
}
public void second(ref Value v, int i)
{
i = 0;
v.i = 20;
Value val = new Value();
v = val;
Console.WriteLine(v.i + " " + i + " ");//15,0
}
}
} 15 0
15
out和ref 可以修饰各种类型out修饰的参数,可以用没有被初始化变量传递给函数,但在函数内必须被赋值。
ref修饰的参数,不可以用没有被初始化的实际参数。但在函数内可以不被赋值