C#传参时前置关键字ref,out,params的区别
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
int n1 = 0;
int a = Get1(n1); // 值传递
Console.WriteLine("n1 = " + n1 + ", a = " + a);
int n2 = 0;
int b = Get2(ref n2); // 引用传递, 变量须初始化, 调用时须在变量前加ref
Console.WriteLine("n2 = " + n2 + ", b = " + b);
int n3;
int c = Get3(out n3); // 引用传递, 变量不须初始化, 调用时须在变量前加out
Console.WriteLine("n3 = " + n3 + ", c = " + c);
int n4 = 0;
int d1 = Get4(n4, 10);
int d2 = Get4(n4, 10, 20, 30); // 不定长数组传递, 调用时不须在变量前加params
Console.WriteLine("n4 = " + n4 + ", d1 = " + d1 + ", d2 = " + d2);
Console.ReadLine();
}
static int Get1(int p)
{
return p + 10;
}
static int Get2(ref int p)
{
p += 10;
return p;
}
static int Get3(out int p)
{
p = 100;
p += 10;
return p;
}
static int Get4(int p, params int[] q)
{
return p + q.Sum();
}
}
}
运行结果如下图所示:

本文详细探讨了C#编程中ref、out和params三个关键字在传递参数时的不同用法和特点。ref关键字用于在方法调用中按引用传递参数,保证参数值的修改在调用者和被调用者之间同步;out关键字类似,但参数必须在方法内部初始化;params关键字则允许传入可变数量的参数,作为数组传入方法。

1485

被折叠的 条评论
为什么被折叠?



