当前位置:编程学习 > asp >>

param数组参数

param数组允许我们只写一个方法, 就能接受数量可变的参数. 这种技术就是参数数组,它本质上是用params关键字来声明的一个参数.而且不仅可以声明params int[] list这样的数组,还可以声明object类型的参数组,参数可以是任意类型的~
Util类
#region Using directives
using System;
#endregion
 
namespace ParamsArray
{
    class Util
    {
        public static int Sum(params int[] paramList)
        {
            if (paramList == null)
            {
                throw new ArgumentException("Util.Sum: null parameter list");
            }
 
            if (paramList.Length == 0)
            {
                throw new ArgumentException("Util.Sum: empty parameter list");
            }
 
            int sumTotal = 0;
            foreach (int i in paramList)
            {
                sumTotal += i;
            }
            return sumTotal;
        }
 
        public static void Everyone(params object[] paramobject)
        {
            if (paramobject == null)
            {
                throw new Exception("Util.Everyone: null parameter list");
            }
 
            if (paramobject.Length == 0)
            {
                throw new Exception("Util.Everyone: empty parameter list");
            }
 
            foreach (object i in paramobject)
            {
                Console.WriteLine(i);
            }
        }
    }
}
Program类
#region Using directives
 
using System;
using System.Collections.Generic;
using System.Text;
 
#endregion
 
namespace ParamsArray
{
    class Program
    {
        static void Entrance()
        {
            Console.WriteLine(Util.Sum(10, 9, 8, 7, 6, 5, 4, 3, 2, 1));     
        }
 
        static void Entrance01()
        {
            Console.WriteLine(Util.Sum());      //长度为0
        }
 
        static void Entrance02()
        {
            Console.WriteLine(Util.Sum(null));  //数组为null
        }
 
        static void Entrance03()
        {
            Util.Everyone("dkjf", 45, "654", 451.5);
        }
 
        static void Main()
        {
            try
            {
                Entrance();
                Entrance01();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex.Message);
            }
 
            try
            {
                Entrance02();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex.Message);
            }
 
            try
            {
                Entrance03();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex.Message);
            }
        }
    }
}
每个try语句执行后,try语句内部的在Exception之后的部分就不会再执行了,所以要另外再写一个try语句。
语句的执行效果如下:

补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,