好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解C#中三个关键字params,Ref,out

关于这三个关键字之前可以研究一下原本的一些操作

?

using system;

using system.collections.generic;

using system.text;

namespace paramsrefout

{

   class program

   {

     static void changevalue( int i)

     {

       i=5;

       console.writeline( "the changevalue method changed the value " +i.tostring());

     }

     static void main( string [] args)

     {

       int i = 10;

       console.writeline( "the value of i is " +i.tostring());

       changevalue(i);

       console.writeline( "the value of i is " + i.tostring());

       console.readline();

     }

   }

}

观察运行结果发现

值并没有被改变,也就是说此时的操作的原理可能也是跟以前c语言的函数操作是一样的

本文主要讨论params关键字,ref关键字,out关键字。

  1)params关键字,官方给出的解释为用于方法参数长度不定的情况。有时候不能确定一个方法的方法参数到底有多少个,可以使用params关键字来解决问题。

?

using system;

using system.collections.generic;

using system.text;

namespace paramsrefout

{

   class number

   {

     public static void useparams( params int [] list)

     {

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

       {

         console.writeline(list[i]);

       }

     }

     static void main( string [] args)

     {

       useparams(1,2,3);

       int [] myarray = new int [3] {10,11,12};

       useparams(myarray);

       console.readline();

     }

   }

}

  2)ref关键字:使用引用类型参数,在方法中对参数所做的任何更改都将反应在该变量中

?

using system;

using system.collections.generic;

using system.text;

namespace paramsrefout

{

   class number

   {

     static void main()

     {

       int val = 0;

       method( ref val);

       console.writeline(val.tostring());

     }

     static void method( ref int i)

     {

       i = 44;

     }

   }

}

  3) out 关键字:out 与ref相似但是out 无需进行初始化。

以上所述是小编给大家介绍的c#中三个关键字params,ref,out,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

dy("nrwz");

查看更多关于详解C#中三个关键字params,Ref,out的详细内容...

  阅读:39次