C#可变变量Params,out,ref

out在使用之前必须在方法里面为out参数赋值,out参数无法获取传递进来的变量的值,只能给传递进来的变量赋值,out参数在方法执行完毕之前必须赋值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            //一个方法只有一个返回值,只能return一个值,当需要返回多个值的时候,可以用out
            int m, n;
            Test(out m, out n);
            Console.WriteLine(m + "-----------" + n);

            //int.TryParse方法的返回值为布尔类型,转换成功返回真,失败返回假
            //但是还得取到转换成功后的值,就用了out参数,来把转换成功后的值传出来
            string s = "333";
            int r;
            bool b = int.TryParse(s, out r);
            if (b)
            {
                Console.WriteLine("转换成功,值为{0}", r);
            }
            else
            {
                Console.WriteLine("转换失败,值为{0}", r);
            }


            //ref,
            int p = 1000;
            Test1(ref p);
            Console.WriteLine(p);
            Test2(ref p);
            Console.WriteLine(p);

            Console.ReadKey();
        }

        public static void Test(out int m, out int n)
        {
            m = 100;
            n = 10;
        }

        public static void Test1(ref int a)
        {
            a = a + 100;
        }

        public static void Test2(ref int b)
        {
            b = b + 10;
        }
    }
}

可变参数
如果方法有多个参数,可变参数必须在最后一个,
可变参数可以传递参数,也可以不传递参数,不传递参数,则args数组为一个长度为0的数组。
可变参数可以直接传递一个数组进来。

public static void Abc(string msg,params int[] args) { }

使用的时候

int[] ss = new int []{ 1, 2, 1, 2, 1 };
            Abc("123", ss);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值