zoukankan      html  css  js  c++  java
  • C#:使用ref,out关键词定义返回值函数

    代码
    static int xValue(ref int num, ref int num2)
            {
                num 
    = 2 * num;
                num2 
    = 2 * num2;
                
    return num;
            }
            
    static void Main(string[] args)
            {
                
    int num = 5;
                
    int num2 = 10;
                Console.WriteLine(xValue(
    ref num, ref num2));
                Console.WriteLine(num 
    + ":" + num2);
                
    //这时的num=10, num2=20;输出结果:10:20;加上ref后会影响到函数外面的变量
            }

    两个注意点:
    1:定义函数时.指定参数的数据类型与函数体外面定义的变量类型一致,static int xValue(ref int num, ref int num2)
    2:使用此函数时为每个参数加上ref.如果不加的话则不会影响函数外面变量的值

    代码
    static int MaxValueL(int[] numArry, out int maxIndex, out int maxIndex2)
            {
                
    int MaxValue = numArry[0];
                maxIndex 
    = 0;
                maxIndex2 
    = 100;
                
    for (int i = 1; i < numArry.Length; i++)
                {
                    
    if (MaxValue < numArry[i])
                    {
                        MaxValue 
    = numArry[i];
                        maxIndex 
    = i;
                    }
                }
                
    return MaxValue;
            }
            
    static void Main(string[] args)
            {
                
    int maxIndex;
                
    int maxIndex2;
                
    int[] numArr = { 14334119933 };
                Console.WriteLine(MaxValueL(numArr, 
    out maxIndex, out maxIndex2));
                
    //返回函数体内的变量MaxValue
                Console.WriteLine(maxIndex + 1);
                
    //返回函数体内的变量maxIndex
                Console.WriteLine(maxIndex2);
                
    //返回函数体内的变量maxIndex2
                Console.ReadKey();
            }

    两个注意点:
    1:定义函数时.指定输出参数的数据类型与函数体外面定义的变量类型一致,out int maxIndex, out int maxIndex2
    2:使用此函数时为想要输出参数加上 out .
    这里的输出是指把函数体内的变量输出到函数体外应用.这也关联到了变量的作用域问题.

     

  • 相关阅读:
    CPP Info Memo part3
    在Google搜索结果显示原始链接(转自 月光博客)
    libc 之 locales
    Git 分支管理与本地 repository 创建
    py2exe issue: ImportError: No module named _fontdata_enc_winansi (http://stackoverflow.com/)
    CPP Info Memo (Part 1)
    CPP Info Memo part2
    HOWTO: Increase write speed by 'aligning' FAT32(通过对齐 FAT32 提高U盘访问速度, 转载)
    (转载)Gentoo中文man乱码
    如何选择开源许可证?(转载)
  • 原文地址:https://www.cnblogs.com/hantianwei/p/1845711.html
Copyright © 2011-2022 走看看