zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }

  • 相关阅读:
    UESTC 250 windy数 数位dp
    hdu 3555 bomb 数位dp
    hdu 2089 不要62 数位dp入门
    poj 3740 Easy Finding 精确匹配
    codeforces 589F. Gourmet and Banquet 二分+网络流
    hdu 3572 Escape 网络流
    hdu 3572 Task Schedule 网络流
    POJ 1823 Hotel 线段树
    2016年,机器学习和人工智能领域有什么重大进展?
    【由浅入深的VR技术之旅】初学VR要解决的三个核心技术问题
  • 原文地址:https://www.cnblogs.com/yuananyun/p/1924244.html
Copyright © 2011-2022 走看看