c#中的params 关键字

      要接受未知数目的参数,可以使用关键字params,该关键字用于参数列表中,声明参数列表最后面的值。params关键字与数组一起使用。

      当值被传递给方法时,编译器首先查看是否有匹配的方法。如果有,则调用该方法;如果没有,编译器将查看是否有包含参数params的方法。如果找到这样的方法,则使用它。编译器将这些值放到一个数组中,并将该数组传递给方法。

      下面两个实例:

       实例一:使用未知数目的参数

       实例二:使用params来指定多种数据类型

 

 

实例一代码:

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

namespace ConsoleAppTest
{
    public class AddEm {

        public static long Add(params int[] args) {
            int ctr = 0;
            long Total = 0;

            for (ctr = 0; ctr < args.Length; ctr++) {
                Total += args[ctr];
            }
            return Total;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            long Total = 0;
            Total = AddEm.Add(1);
            Console.WriteLine("Total1={0}",Total);
            Total = AddEm.Add(1,2);
            Console.WriteLine("Total2={0}", Total);
            Total = AddEm.Add(1,2,3);
            Console.WriteLine("Total3={0}", Total);
            Total = AddEm.Add(1,2,3,4);
            Console.WriteLine("Total4={0}", Total);
            Console.Read();
        }
    }
}

实例二代码:

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

namespace ConsoleAppTest
{
    public class Garbage {
        public static void Print(params object[] args) {
            int ctr = 0;
            for (ctr = 0; ctr < args.Length; ctr++) {
                Console.WriteLine("Argument {0} is:{1}",ctr,args[ctr]);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            long ALong = 1234567890123456789L;
            decimal ADec = 1234.5M;
            byte Abyte = 42;
            string AString = "Cole McCrary";
            Console.WriteLine("First call...");
            Garbage.Print(1);
            Console.WriteLine("/nSecond call...");
            Garbage.Print();
            Console.WriteLine("/nThird call...");
            Garbage.Print(ALong,ADec,Abyte,AString);
            Console.WriteLine("/nFourth call...");
            Garbage.Print(AString,"is cool","!");
            Console.Read();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Daniel的技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值