Home > Article > Backend Development > C# difficulties are solved one by one (2): out return parameters
Pass by value (by value) and pass by address (by reference) are the ordinary method of passing parameters and the method of ref declaration respectively. The pass by address method needs to be modified with the ref keyword before use; out is the output return transfer, which has many similarities with ref. , the important difference is that the ref mentioned in the previous section must be initialized in the referenced method; out must have a return value in the referenced method.
using System; /****************************** * Chapter:C#难点逐个击破(一) * Author:王洪剑 * Date:2010-1-15 * Blog:http://www.51obj.cn/ * Email:walkingp@126.com * Description:重点讲解输出参数out * ***************************/ namespace TestOut { class Program { /// <summary> /// out的输出值、返回值 /// </summary> /// <param name="name"></param> /// <returns></returns> static string OutResultMethod(out string name) { string _name = "Wang Hongjian"; name = _name; string __name = "Zheng Zi"; return __name; } static void Main(string[] args) { string _name = "Zhang Yu"; Console.WriteLine("调用前:{0}", _name); string result= OutResultMethod(out _name); Console.WriteLine("调用后:{0}",_name); Console.WriteLine("返回结果:{0}",result); Console.ReadKey(); } } }
Run results:
out is used more in actual projects. This is because out can return multiple values.
class Program { /// <summary> /// out的输出值、返回值 /// </summary> /// <param name="name"></param> /// <returns></returns> static string OutResultMethod(out string name,out string password) { string _name = "Wang Hongjian"; name = _name; string _password = "123456"; password = _password; string __name = "Zheng Zi"; return __name; } static void Main(string[] args) { string _name = "Zhang Yu"; string _password; Console.WriteLine("调用前:{0}", _name); string result = OutResultMethod(out _name, out _password);//多个参数传递 Console.WriteLine("调用后:{0}",_name); Console.WriteLine("返回结果:{0}",result); Console.ReadKey(); } }
Associating multiple parameters, you must have thought of using arrays. Yes, using arrays is a good idea. A good way is that the array itself packages and "encapsulates" parameters of the same type into an object and passes them to the method, which can simplify the writing of multi-parameter methods and achieve an effect similar to overloading.
static void OutArrayMethod(out string[] strArr) { int i = 0; string[] _strArr = new string[10]; while (i < _strArr.Length) { _strArr[i] = "第" + i + "个成员"; i++; } strArr = _strArr; } static void Main(string[] args) { string[] _strArr=new string[10]; OutArrayMethod(out _strArr); foreach (string str in _strArr) { Console.WriteLine(str); } Console.ReadKey(); }
Operation effect:
The above is the content of the C# difficulty to break down one by one (2):out return parameter. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!