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();
            }
        }
    }

  • 相关阅读:
    TCP/IP详解学习笔记
    python 中颜色的表示
    token工作原理
    sql注入相关链接记一次SQL注入实战
    python读写不同编码txt文件
    selenium+python 优化测试报告
    一个非常好的Linux学习网站
    jmeter 正则表达式 练习
    jmeter 实战项目总结2——微信端
    jmeter 实战项目总结1
  • 原文地址:https://www.cnblogs.com/yuananyun/p/1924244.html
Copyright © 2011-2022 走看看