1. 值类型的参数
正常的参数语法格式
语法:参数类型参数名
Public void testCommand(int x)
{
}
2. 引用类型的参数
使用原因:
当我们想通过函数改变函数外面的值,那么就将其地址传递进去。
语法:ref 参数类型 参数名
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
public void testInt(int x)
{
x = 1;
}
public void testRef(ref int x)
{
x = 2;
}
static void Main(string[] args)
{
int x = 0;
Program p = new Program();
p.testInt(x);
Console.WriteLine("正常参数x=" + x);
p.testRef(ref x);
Console.WriteLine("引用参数x=" + x);
}
}
}
运行结果:
正常参数x=0
引用参数x=2
思考:
函数参数加上ref,以及引用的时候加上ref,那么就相当于把地址传进去,那么修改了ref参数的值,那么就会改变原值,而没有ref的,那么就不会影响其值。
3. 输出参数
原因:有时方法计算的结果有多个,而return语句一次只能返回一个结果,这时候就要用到out关键字,使用out关键字表明该引用参数是用于输出的,而且调用该参数时不需要对参数进行初始化,
语法格式:
out 参数类型 参数名
example:
声明函数:
Class program
{
Public int testOut(out x,out y)
{
x=1;
y=2
int z;
z=1+2;
return z;
}
}
调用函数
int x=0,y=0,z=0;
program p=new program();
z=p.testOut(out x,out y);
运行的结果:
X=1;y=2;z=1+2=3;
4. 数组型参数
原因:
当需要传递的参数个数不确定时,如求几个数的和,由于没有规定是几个数,运行程序时,每次输入值的个数不一定一样。为了解决这个问题,c#语言采用params关键字来表明参数的个数是不确定的。
语法:
Params 参数类型 参数名
注:参数类型必须是数组。
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
public void testParam(params object[] nums)
{
for(int i=0;i<nums.Length;i++)
Console.WriteLine(nums[i]);
}
static void Main(string[] args)
{
int x = 0;
int y = 0;
int z = 0;
Program p = new Program();
p.testParam(x, y, z,3,4,"65",'c',"ddd");
Console.ReadLine();
}
}
}
运行结果:
0
0
0
3
4
65
c
ddd