C#方法调用传递的参数分四类:
- 默认的值参数(value parameter); //传递复制品
- 引用参数(reference parameter),关键字"ref";//传递引用指针
- 输出参数(output parameter),关键字"out"。//方法返回一个以上的返回值时使用
- 数组参数(array parameter),关键字"params"
下边我介绍一下ref 和out的参数,这种参数是大有用处的,因为它传递的是参数的地址。所以可以解决函数只有一个返回值的问题。看示例代码
参考网址:http://www.cnblogs.com/jht/archive/2005/07/18/194935.aspx
http://dev.csdn.net/article/46/46297.shtm
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
static void
{
int refionx = 5;
Sqrue(ref refionx);//传递的为refionx所在的地址
Console.WriteLine("{0}:",refionx);//这时refionx所指向的地址内的值为原来值的平方
}
static void Sqrue(ref int x)//将地址内的值取平方
{
x = x * x;
}
}
}
Ref 与 Out的区别在于,数组类型的 ref 参数必须由调用方明确赋值,使用数组类型的 out 参数前必须先为其赋值
下边是分别用ref 和Out写的两个例子
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
static void
{
int[] myArray =new int [5]{1,2,3,4,5};
FillArray(ref myArray);
for (int i=0; i < myArray.Length; i++)
Console.WriteLine(myArray[i]);
}
static public void FillArray(ref int[] myArray)
{
// Initialize the array:
myArray[0] = 123;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
static void
{
int[] myArray; // Initialization is not required
FillArray(out myArray);
for (int i=0; i < myArray.Length; i++)
Console.WriteLine(myArray[i]);
}
static public void FillArray(out int[] myArray)
{
// Initialize the array:
myArray = new int[5] { 1, 2, 3, 4, 5 };
}
}
}
最后我介绍一下params类型参数在用到数组参数的时候需要注意下边几个问题
1. 数组参数只能是一维的;
2. 如果有多个输入参数,就只允许一个输入参数是params参数,而且它必须是参数表中的最后一个。
请看示例:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication15
{
class Program
{
public static void Add(params int[] args)
{
int Count = 0;
foreach (int d in args)
{
Count += d;
}
Console.WriteLine("{0}",Count);
}
static void
{
int[] a = new int[5] { 1, 2, 3, 4, 5 };
Add(a);
}
}
}
浙公网安备 33010602011771号