C#:params 关键字的学习

http://www.cnblogs.com/muzihai1988/archive/2011/02/11/1951542.html

 

今天看到了params,以前没用过就顺手学习了一下。

params 关键字有以下几大特点:

  • params 关键字可以指定采用数目可变的参数的方法参数(不指定参数的数目)。
  •  可以发送参数声明中所指定类型的逗号分隔的参数列表或指定类型的参数数组。
  • 可以不传递参数。
  • 在方法声明中的 params 关键字之后不允许任何其他参数,并且在方法声明中只允许一个 params 关键字。

 

View Code
    
    
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ConsoleApplication5
7 {
8 public class MyClass
9 {
10 public static void UseParams( params int [] list)
11 {
12 for ( int i = 0 ; i < list.Length; i ++ ) {
13 Console.Write(list[i] + " " );
14 }
15 Console.WriteLine();
16 }
17
18 public static void UseParams2( params object [] list)
19 {
20 for ( int i = 0 ; i < list.Length; i ++ ) {
21 Console.Write(list[i] + " " );
22 }
23 Console.WriteLine();
24 }
25
26 static void Main()
27 {
28 // You can send a comma-separated list of arguments of the specified type.
29 // 你可以用一个逗号分隔的序列的参数指定的类型。
30 UseParams( 1 , 2 , 3 , 4 );
31 UseParams2( 1 , ' a ' , " test " );
32
33 // A params parameter accepts zero or more arguments. 
34 // 一个params参数接受零个或多个参数。
35 // The following calling statement displays only a blank line. 
36 // 以下称声明显示的只有一个空白行。
37 UseParams2();
38
39 // An array argument can be passed, as long as the array
40 // type matches the parameter type of the method being called.
41 // 只要数组类型符合方法的参数类型,就可以被调用
42 int [] myIntArray = { 5 , 6 , 7 , 8 , 9 };
43 UseParams(myIntArray);
44
45 object [] myObjArray = { 2 , ' b ' , " test " , " again " };
46 UseParams2(myObjArray);
47
48 // The following call causes a compiler error because the object
49 // array cannot be converted into an integer array.
50 // UseParams(myObjArray);
51
52 // The following call does not cause an error, but the entire
53 // integer array becomes the first element of the params array.
54 UseParams2(myIntArray);
55 }
56 }
57 }
58

其实params 关键字用法挺灵活的!在以后可以尝试用!

(本文参考了MSDN:http://msdn.microsoft.com/zh-cn/library/w5zay9db(v=VS.100).aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值