天天看点

params,out和ref的关键字区别

(一)params---------可以让参数随意变化的关键字

1 staticvoid Main(string[] args)

2 {

3 TestParams(1, 2, 3);

4 TestParams(1, 2, 3, 4, 5, 6);//注意参数随意变换

5

6 TestParams2(1, "a", "b", 12, 52, 16);

7

8 Console.ReadLine();

9 }

10

11 staticvoid TestParams(paramsint[] list)

12 {

13 string str =string.Empty;

14 for (int i =0; i < list.Length; i++)

15 {

16 str = str + list[i] +";";

17 }

18 Console.WriteLine(str);

19 }

20

21 staticvoid TestParams2(paramsobject[] list)

22 {

23 string str =string.Empty;

24 for (int i =0; i < list.Length; i++)

25 {

26 str = str + list[i] +";";

27 }

28 Console.WriteLine(str);

29 }

(二)out------一个引用传递

   因为传递的不是值,而是引用,所以对out参数做的任何修改都会反映在该变量当中

static void Main(string[] args)
        {
            string str;    //str不必初始化,因为str进入方法后,会清掉自己,使自己变成一个干净的参数,

              //也因为这个原因,在从方法返回前,必须给str赋值,否则会报错。

            TestOutPar(out str);

            Console.WriteLine(str);
            Console.ReadLine();
        }

        static void TestOutPar(out string str)
        {
            str = "hello!";
        }
      

    结果显示:"hello!"

       如果在TestOutPar方法里注释掉 //str = "hello!";那么程序会报错

  

params,out和ref的关键字区别

  用途:

  当希望一个方法能够返回多个值时,这个out就变得非常有用。比如在分页方法中,我们需要返回当前页,页数等等数据。

3 int pageCount;

4 int pageSize;

5 string result=TestOutPar(out pageCount, out pageSize);

6

7 Console.WriteLine(pageCount);

8 Console.WriteLine(pageSize);

9 Console.WriteLine(result);

10 Console.ReadLine();

11 }

12

13 staticstring TestOutPar(outint pageCount, outint pageSize)

14 {

15 pageCount =100;

16 pageSize =12;

17 return"hello!";

18 }

19

20   结果显示:100,12,hello!

(三)ref-----------仅仅是一个地址

3 int value =10;//必须初始化,因为value进入方法后还是他自己,也因为这个原因,value可以在方法内不操作

4 TestRefPar(ref value);

5 Console.WriteLine(value);

6 Console.ReadLine();

7 }

8

9 staticstring TestRefPar(refint value)

10 {

11 //value = 100;  //value在方法内不操作

12 return"hello!";

13 }

继续阅读