zoukankan      html  css  js  c++  java
  • 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!";那么程序会报错

      

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

    1 staticvoid Main(string[] args)
    2 {
    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   结果显示:10012,hello!

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

    1 staticvoid Main(string[] args)
    2 {
    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 }
  • 相关阅读:
    微信小程序创建第一个项目
    微信小程序工具下载与安装
    Windows下删除顽固文件夹
    微信小程序账号注册
    C++第四十九篇 -- 将一个项目Copy到另一台电脑
    C++第四十八篇 -- 字符串分离方法
    C++第四十七篇 -- VS2017带参数启动调试程序
    MarkDown插入图片
    Http升级到Https (本地测试,无须域名和认证)
    语音识别(ASR) 阿里云
  • 原文地址:https://www.cnblogs.com/jackyfei/p/Ref_Out.html
Copyright © 2011-2022 走看看