C# 方法后形参的高级使用 params、ref、out
- params 可变参数,如下代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace blog { class Program { static void Main(string[] args) { int[] a = paramDemo(1,2,3,4); Console.WriteLine(a.Length); int[] arr = { 1, 2, 3, 4, 5, 6 }; int[] b = paramDemo(arr); Console.WriteLine(b.Length); Console.ReadLine(); } /// <summary> /// 可变参数,在参数前面添加params关键字,比如 /// 下面方法是要传入一个int数组类型。那么,加入params后 /// 调用的时候直接传入一个 例如pparamDemo(1,2,3)这样一个 数组也是不会报错的 /// 但是注意参数列表必须是参数的最后一个参数才可以 /// </summary> /// <param name="arr"></param> public static int[] paramDemo(params int[] arr) { return arr; } } }
- ref
ref关键字用于将方法内的变量改变后带出方法外。具体我们通过例子来说明:
例子中,将变量n1和n2交换了。如果没有加ref参数,由于没有swadDemo()方法没有返回值,调用后,n1和n2是不会交换的,但是加了ref后,变量便会在swadDemo()中改变后并带出。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace blog { class Program { static void Main(string[] args) { refDemo(); } #region 使用高级参数ref private static void refDemo() { int n1 = 1; int n2 = 2; swadDemo(ref n1, ref n2); Console.WriteLine("n1:" + n1 + "\r\n" + "n2:" + n2); Console.ReadLine(); } #endregion #region 高级参数ref用法 public static void swadDemo(ref int a, ref int b) { //注意,这个方法中,并没有返回值。但是,由于加了ref, //所以会将变量改变后再带出。 //ref参数,用于将方法内的变量改变后带出方法外 int temp; temp = a; a = b; b = temp; } #endregion } }
- out
用于在方法中返回多余值。(可以理解为让一个方法返回不同的类型值)
我们通过例子来理解例子的功能:用一个方法,判断用户是否登陆成功(布尔类型),同时提示用户是否登陆成功(字符串类型)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace blog { class Program { static void Main(string[] args) { string str; Console.WriteLine("请输入用户名"); string uersname = Console.ReadLine(); Console.WriteLine("请输入密码"); string password = Console.ReadLine(); //传入参数也一样要在参数前面添加一个out bool b = login(uersname, password, out str); if (b) { Console.WriteLine(str); } else { Console.WriteLine(str); } Console.ReadKey(); } public static bool login(string name, string pwd, out string msg) { //如果需要返回多个参数,则添加多个参数即可,例如login(string name, string pwd, out string msg,out int num) //out多余返回值,用于一个方法中多余返回的值,例如这个方法中, //返回值是布尔类型,同时,还可以返回一个多余的值,msg //out的参数必须在方法中进行初始化 bool result; if (name == "admin" && pwd == "123") { msg = "登陆成功"; result = true; } else { msg = "登陆失败"; result = false; } return result; } } }