c#中的Out, params,ref 细说并沉淀
1. Out,params,ref之前先记录平时用的最多的按值传递参数的情况,当然默认情况下参数传入函数的默认行为也是按值传递的。
1: //默认情况下参数会按照值传递2: static int add(int x,int y) {3: int ans = x + y;4: x = 1000; y = 2000;5: return ans;6: }1: static void Main(string[] args) {2: Console.WriteLine("默认情况下按值传递");3: int x = 3, y = 8;4: Console.WriteLine("调用前:x:{0},y:{1}",x,y);5: Console.WriteLine("调用后的结果:{0}",add(x,y));6: Console.WriteLine("调用后:x:{0},y:{1}",x,y);7: Console.ReadLine();8: }输出的结果跟我们预期的一样:
2.Out修饰符
1: static void add(int x,int y,out int ans) {2: ans = x + y;3: }
Main里面可以这么写:
1: int ans;2: add(20, 20, out ans);3: Console.WriteLine("20+20={0}", ans);4: Console.ReadLine();输出的结果当然是:20+20=40啦,这个在原来如果没有用out的话那会出现“使用了未赋值的局部变量”。
那即使我们给ans赋值如:int ans=10;
它在调用add方法之后也不会改变,因为调用的方法根本不知道里面发生了什么。
这样就变成了20+20=10了,显然是错的。
当然Out的最大的亮点,就是在一个函数调用之后可以输出多个参数值。
将上面的方法改为:
1: static void setParams(out int x,out string y,out bool ans) {2: x = 2;3: y = "YeanJay";4: ans = true;5: }我们在Main里面可以这么写:
上一个:利用C#实现分布式数据库查询
下一个:c#把汉字转化成全拼音函数(全拼)