C# params ref out 使用小结

params 关键字可以指定在参数数目可变处采用参数的方法参数。

params 关键字在方法成员的参数列表中使用,为该方法提供了参数个数可变的能力,它在只能出现一次并且不能在其后再有参数定义(之前可以),必须在参数末尾处声明。param array只能是一维,而且不能用 ref 或者 out 修饰.

示例:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class App
{
//第一个参数必须是整型,但后面的参数个数是可变的。
//而且由于定的是object数组,所有的数据类型都可以做为参数传入
public static void UseParams(int id, params object[] list)
{
Console.WriteLine(id);
for (int i = 0; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
}

static void Main()
{
//可变参数部分传入了三个参数,都是字符串类型
UseParams(1, "a", "b", "c");
//可变参数部分传入了四个参数,分别为字符串、整数、浮点数和双精度浮点数数组
UseParams(2, "d", 100, 33.33, new double[] {1.1, 2.2});

Console.ReadLine();
}
}
}

ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。

  使用ref前必须对变量赋值,out不用。

  out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。

  区别可以参看下面的代码:

using System;
class TestApp
{
 static void outTest(out int x, out int y)
 {//离开这个函数前,必须对x和y赋值,否则会报错。
  //y = x;
  //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
  x = 1;
  y = 2;
 }
 static void refTest(ref int x, ref int y)
 {
  x = 1;
  y = x;
 }
 public static void Main()
 {
  //out test
  int a,b;
  //out使用前,变量可以不赋值
  outTest(out a, out b);
  Console.WriteLine("a={0};b={1}",a,b);
  int c=11,d=22;
  outTest(out c, out d);
  Console.WriteLine("c={0};d={1}",c,d);

  //ref test
  int m,n;
  //refTest(ref m, ref n);
  //上面这行会出错,ref使用前,变量必须赋值

  int o=11,p=22;
  refTest(ref o, ref p);
  Console.WriteLine("o={0};p={1}",o,p);
 }
}
posted @ 2010-10-30 08:46  Kingdom_0  阅读(305)  评论(0编辑  收藏  举报