C#关于params的用法(使用数量可变的参数)
有些方法需要传递个数不定的值进行运算。比如求最小值的方法。除了用容器外,还可以使用params来做
例子如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace cxx { class Min { public int MinVal(params int[] nums) { int m; if (nums.Length == 0) { Console.WriteLine("Error, no data is found "); return 0; } m = nums[0]; for (int i = 1; i < nums.Length; i++) if (nums[i] < m) m = nums[i]; return m; } class TestParams { static void Main() { Min ob = new Min(); int min; int a = 10, b = 20; //call with 2 values min = ob.MinVal(a, b); Console.WriteLine("Minimum is " + min); //call with 7 values int[] args = new int[] { 61, 34, 5, 11, 343, 13, 7 }; min = ob.MinVal(args); Console.WriteLine("Minimum is " + min); Console.WriteLine(@"my name is shoneworn. welcome to my blog: www.cnblogs.com/shoneworn. 注意看@的用法,是按照自己排版输出的。"); Console.ReadKey(); } } }
运行效果:
不积跬步,无以至千里。