C#中的参数前缀ref,out和params关键字
- 刚开始写博客,主要是帮自己记录下学习的一些零零碎碎,如果对你有所帮助当然是最好的。
在C#中有些参数前会出现ref,out,params关键字,每个都有不同的含义
- ref的用法—引用
就是强制按引用传递参数的关键字,可以用在值类型和引用类型。需要注意的是在使用时不仅声明中要在参数前加ref,如public void Add(ref x,ref y){…}.而且调用时也需要加上ref,如Add(ref num1,ref num2) .
class Program
{
static void Main(string[] args)
{
int x = 5, y = 6;
Add(ref x, y);
Console.WriteLine( "x =" + x +"\ny =" + y );
Console.ReadLine();
}
static void Add(ref int x,int y)
{
x = 7;
y = 9;
}
}
运行结果
- out的用法----输出参数
在C#中有一种正规的标记需要返回参数的关键字,就是out关键字,通过在声明和调用时使用out可以实现返回参数的操作
当然能实现返回参数还有返回值,引用或指针传递的方法。
class Program
{
static void Main(string[] args)
{
int x=5,y=6,sum;
Add(x,y,out sum);
Console.WriteLine(x + "+" + y + "=" + sum);
Console.ReadLine();
}
static void Add(int x,int y,out int sum)
{
sum = x + y;
}
}
运行结果
3. params的用法----不定数目的参数
在C#中允许方法带有不定数目的参数,用params关键字,且参数是参数列表的最后一个参数
static void Main(string[] args)
{
fun("Call 1");
Console.WriteLine("\n");
fun("Call 2", 2);
Console.WriteLine("\n");
fun("Call 3", 3.2, "This is a bad thing!");
Console.ReadLine();
}
static void fun(string str,params object[] args)
{
Console.WriteLine(str);
foreach(object ob in args)
{
if (ob is int)
{ Console.WriteLine("int:" + ob);
}
else if(ob is double)
{
Console.WriteLine("double:" + ob);
}
else
{
Console.WriteLine(ob);
}
}
}
运行结果