C#函数的值所谓的几种传递方式
一、值传递
是c#默认的值传递方式,原理就是将你的实参复制一份到传给函数的形参,调用时新创立一个存储位置,两者位置不同,互不影响。
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
int a = 5;
Program hh = new Program();
hh.test(a);
}
public void test(int a)
{
Console.WriteLine("运算前:"+ a);
a *= a;
Console.WriteLine("运算后:"+a);
}
}
}
输出:
运算前:5
运算后:25
二、引用传递(ref)
这种传递模式故名思意,即使引用你原来那个值所存储的位置,去引用它得到使用。直接使用原来的数据,不会创建新的存储位置,若进行运算会对数据有更改,这里使用 ref 关键字进行引用值传递
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
int a = 5;
Program hh = new Program();
Console.WriteLine("函数调用前:" + a);
hh.test(ref a);
Console.WriteLine("函数调用后:" + a);
}
public void test(ref int a)
{
a *= a;
Console.WriteLine("函数运行:" + a);
}
}
}
输出:
函数调用前:5
函数运行:25
函数调用后:25
三、输出传递(out)
输出传递和引用传递类似,但不完全相同,其区别是,用 out 关键字进行输出传递可以传输很多个值。不同于return只返回一个。输出传递不返回到函数而是直接返回原来的存储位置的数据。
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
int a = 5;
int b = 5;
Program hh = new Program();
Console.WriteLine("函数调用前:" + a);
Console.WriteLine("函数调用前:" + b);
hh.test(out a,out b);
Console.WriteLine("函数调用后:" + a);
Console.WriteLine("函数调用前:" + b);
}
public void test(out int a ,out int b)
{
int c= 10;
a = c;
b = c;
a *= a;
b *= b;
}
}
}
输出
函数调用前:5
函数调用前:5
函数调用后:100
函数调用前:100
欢迎大家交流和讨论~~