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

  • 相关阅读:
    Spring实践第三天 (SpringDI:依赖注入)
    单例模式(Singleton)
    Spring IOC 及 Spring 中Bean的三种创建方式
    Spring实践第二天(创建对象的三种基本方式)
    ORA-28374: typed master key not found in wallet
    Unable open dabase as spfile parameter incorrect
    【java/C# 服务器】IOS 配置推送证书 p12文件流程
    第一贱-UILabel
    iOS开发系列--让你的应用“动”起来
    AFNetworking 使用总结
  • 原文地址:https://www.cnblogs.com/yuananyun/p/1924244.html
Copyright © 2011-2022 走看看