1.可选参数与命名参数
设计方法参数时,可为部分或全部参数分配默认值【可选参数】或通过指定参数名称来传递参数。
static void Main(string[] args)
{
test1(2);
test1(2, 3);
test2(2, 4);
//以上为可选参数
//以下为命名参数
test2(width: 4, height: 2);
Console.ReadKey();
}
/// <summary>
/// 有默认值的参数必须放在没有默认值的所有参数之后
/// 如果参数要求ref/out关键字进行标识,不能设置默认值
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public static void test1(int x,int y=2)
{
Console.WriteLine("输出值:{0}",x + y);
}
public static void test2(int height,int width)
{
Console.WriteLine("面积:{0}", height * width);
}
2. 以传引用的方式向方法传递参数
CLR允许以传引用而非传值的方式传递参数。C#用关键字out或ref支持这个功能。两个关键字都告诉编译器生成元数据来指明该参数是传引用的。编译器将生成代码来传递参数的地址,而非传递参数本身。
CLR不区分out和ref,即无论使用哪个关键字,都会生成相同的IL代码,元数据也几乎一致,只有一个bit除外,用于记录方法时指定的是ref还是out。两者的区别在于,使用out时,传递的参数不需要初始化,而使用ref,传递的参数必须要初始化。
static void Main(string[] args)
{
int y;
test(0, out y);
prac(0, ref y);
Console.WriteLine(y);
Console.ReadKey();
}
public static void test(int x,out int y)
{
y = 5;
}
public static void prac(int x, ref int y)
{
y = 5;
}
3. 向方法传递可变数量的参数
static void Main(string[] args)
{
test(1, 2, 2);
test(new int[] { 1, 2, 2 });
Console.ReadKey();
}
/// <summary>
/// 特定类型、任意数量的参数
/// </summary>
/// <param name="arr"></param>
public static void test(params int[] arr)
{
int sum = 0;
if (arr != null && arr.Count() > 0)
{
foreach (var item in arr)
{
sum += item;
}
}
Console.WriteLine(sum);
}
/// <summary>
/// 任意类型、任意数量的参数
/// 调用参数数量可变的方法对性能有所影响,除非显示传递null
/// </summary>
/// <param name="arr"></param>
public static void testExtemn(params object[] arr)
{
if (arr != null && arr.Count() > 0)
{
foreach (var item in arr)
{
Console.WriteLine(item.GetType());
}
}
}
4. 参数和返回类型的设计规范
声明方法的参数类型时,应尽量指定最弱的类型,宁愿要接口也不要基类。
static void Main(string[] args)
{
test("123");//3
Console.ReadKey();
}
/// <summary>
/// 若需要使用方法来处理一组数据项,此时使用接口声明参数,这样,
///所有实现了该接口的类型都可以传参
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
public static void test<T>(IEnumerable<T> collection)
{
if (collection != null && collection.Count() > 0)
{
Console.WriteLine(collection.Count());
}
}