您的位置:首页 > 编程语言 > C#

C# 关键字params、ref 和 out

2012-03-21 11:07 316 查看

一、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
// a
// keywords

// 100
// a
// keywords
// 1111
// s

二、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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: