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 .
    这里的输出是指把函数体内的变量输出到函数体外应用.这也关联到了变量的作用域问题.

     

  • 相关阅读:
    中国的网游,发人深省
    .NET开源Bug管理软件BugTracker.NET使用小记
    开源的学术论文排版软件TeX简介
    在sqlplus中批量执行sql命令
    DotNetBar中ExpandableSplitter使用技巧
    上传一很酷的黑色背景.vssettings文件
    瑞雪兆丰年2008年的第一场雪
    Oracle用Start with...Connect By子句递归查询
    【转载】Making new features with topology tools(ArcInfo and ArcEditor only)
    Geoprocess Execute出错原因?Vb+AE9.2
  • 原文地址:https://www.cnblogs.com/hantianwei/p/1845711.html
Copyright © 2011-2022 走看看