参数浅谈(params ref out)

c#中有四种在方法中传递参数的方法,传值,传址(ref),输出参数(out),数组参数(params)

所有的参数传递都是按值来传递的,所以对引用类型赋值改变不了参数的值

class test
{
void change(int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}
void change2(ref object o)
{
o = new object();

}
static void Main()
{
object obj = 1111;
test t = new test();
t.change2( ref obj);
Console.WriteLine(obj);//所有的参数都是按照值来传递的
Console.Read();
}

}

通过添加ref关键字可以改变传入参数的引用,传入ref关键字时需要赋值

//class test
//{
// static void f( int p)
// {
// Console.WriteLine("p={0}",p);
// p++;
// }
// static void Main()
// {
// int a = 1;
// Console.WriteLine("pre:a={0}",a);
// f( a);
// Console.WriteLine("post:a={0}",a);
// Console.Read();
// }
//}
//class test {
// static void swap(ref int a, ref int b) {
// int t = a;
// a = b;
// b = t;
// }
// static void Main()
// {
// int x = 1;
// int y = 2;
// Console.WriteLine("{0}{1}",x,y);
// swap(ref x, ref y);
// Console.WriteLine("{0}{1}", x, y);
// Console.Read();
// }

//}

out关键字用来返回多个值

//}
//class test {
// static void divide(int a,int b,out int result,out int remainder) {
// result = a / b;
// remainder = a % b;
// }
// static void Main() {
// for (int i = 1; i < 4; i++)
// {
// for (int j = 1; j < 4; j++)
// {
// int result, r;
// divide(i, j, out result, out r);
// Console.WriteLine("{0}/{1}={2},r={3}",i,j,result,r);

// }
// }
// Console.Read();
// }
//}

params关键字可以让方法拥有可变参数,params只能出现在参数列表的最后而且只能出现一次

class Params
// {
// static void Main() {
// Console.WriteLine(sum(1,2,3));
// Console.WriteLine(sum(1, 2, 3,3));
// Console.Read();
// }
// private static int sum(int a,int b,params int[] values) {
// int sum = 0;
// foreach (int val in values)
// sum += val;
// Console.WriteLine("{0},{1}",a,b);
// return sum;

// }
// }

详见:https://www.cnblogs.com/davyli/archive/2008/11/01/1324352.html

posted @ 2018-08-30 15:58  小矮子的小胖子  阅读(218)  评论(0编辑  收藏  举报