C# 关键字params、ref 和 out
一、params
1. 用params修饰的参数,参数列表是可变的。
字面意思比较难懂,所以看示例很有用。
class Program { staticvoid Main(string[] args) { // 一般做法是先构造一个对象数组,然后将此数组作为方法的参数 object[] arr =newobject[3]{100,'a',"keywords"}; UseParams(arr);
// 而使用了params修饰方法参数后,我们可以直接使用一组对象作为参数 // 当然这组参数需要符合调用的方法对参数的要求 UseParams(100,'a',"keywords",1111,'s');// 参数可变 Console.Read(); } publicstaticvoid UseParams(paramsobject[] list) { for(int i =0; i < list.Length; i++) { Console.WriteLine(list[i]); } } } // output: // 100 // 100 |
二、ref
1. Ref使用前必须声明和初始化
2. Ref传递的是地址,修改的是地址,是原样,不是副本。
class Program { staticvoid Main(string[] args) { int i =10;
// 查看调用方法之前的值 Console.WriteLine("Before the method calling: i = {0}", i);
UseRef(ref i);
// 查看调用方法之后的值 Console.WriteLine("After the method calling: i = {0}", i); Console.Read(); }
publicstaticvoid UseRef(refint i) { i +=100; Console.WriteLine("i = {0}", i); } } // output: // Before the method calling: i = 10 // i = 110 // After the method calling: i = 110
|
三、out
1. Out使用前仅需声明
2. out 关键字会导致参数通过引用来传递。这与 ref 关键字类似。
using System;
namespace HelloWorld { classProgram { staticvoid Main(string[] args) { string str = "123"; int result; // 使用out前声明 bool flag = int.TryParse(str, out result); // 尝试将string转化为int Console.WriteLine(result); Console.ReadLine(); } } } // output: // 123
|
作者:樊勇
出处:http://www.cnblogs.com/fanyong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
我的联系方式:fanyong@gmail.com
个人独立博客:www.fy98.com