函数返回多个值
作者:admin 来源: 2022/11/29 9:27:04

1、ref,按地址传递的,使用后都将改变原来参数的数值


static void Main(string[] args)
        {
            int v = 1;
            method1(ref v);
            Console.WriteLine($"从函数传递出来的值:{v}");
        }
        static void method1(ref int v)
        { 
            Console.WriteLine($"从参数传递进来的值:{v}");
            v= 2;
            Console.WriteLine($"在函数内部修改v的值为2");
        }


2、out,按地址传递的,使用后都将改变原来参数的数值

static void Main(string[] args)
        {
            int v = 1;
            method1(out v);
            Console.WriteLine($"从函数传递出来的值:{v}");
        }
        static void method1(out int v)
        {
            v = 100;
            Console.WriteLine($"out 必须初始化一次,初始化为:{v}");
            v= 2;
            Console.WriteLine($"在函数内部修改v的值为2");
        }
总结:ref可以把参数的数值传递进函数。但是out不能传递初始值进去,参数的数值为空,必须初始化一次。ref是有进有出,out是只出不进。


3、元组类(tuple)返回多个值

static void Main(string[] args)
        {         
            //写法1
           //Tuple<int,int> result= method1();
           //写法2
            var result = method1();
            Console.WriteLine($"从函数传递出来的值:{result.Item1}.{result.Item2}");
        }
        static Tuple<int,int> method1()
        {
            //写法1
            //return Tuple.Create(1, 2);
            //写法2
            return new Tuple<int,int>(1, 2 );
        }


4、简洁写法

static void Main(string[] args)
        {                  
            var result = method1();
            Console.WriteLine($"从函数传递出来的值:{result.Item1}.{result.Item2}");
        }
        static (string result1,int result2) method1()
        {
            //写法1
            //return ("1", 2);
            //写法2
            return (result1:"1",result2:2);
        }


称      呼:
联系方式:
您的评论:
技术支持:l.w.dong@qq.com www.luweidong.cn
广州市   wx:lwdred
Copyright © 2014 三味书屋 All Rights Reserved
技术支持:l.w.dong@qq.com  sitemap xml  sitemap html

粤公网安备44010602011869号

粤ICP备13031080号-1