当前位置: 移动技术网 > IT编程>开发语言>c# > 详解C#中三个关键字params,Ref,out

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

2019年07月18日  | 移动技术网IT编程  | 我要评论
关于这三个关键字之前可以研究一下原本的一些操作 using system; using system.collections.generic; using s

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

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,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网