服务器之家

服务器之家 > 正文

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

时间:2022-01-06 12:56     来源/作者:RynerLute

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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

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

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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关键字:使用引用类型参数,在方法中对参数所做的任何更改都将反应在该变量中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

标签:

相关文章

热门资讯

蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部