The transfer value (by value) and the address (by reference) are common pass parameters and ref declarations respectively, and the method of the address requires REF keyword modification before use, and out returns the pass for output, which is the same as ref. The important difference is that the ref mentioned in the previous section must be initialized in the referenced method, and out must have a return value in the referenced method.
Copy Code code as follows:
Using System;
/******************************
* chapter:c# Difficult to break (i)
* Author: Wang Hongjian
* DATE:2010-1-15
* blog:http://www.51obj.cn/
* email:walkingp@126.com
* Description: Focus on the output parameters out
* ***************************/
Namespace Testout
{
Class Program
{
<summary>
Out output value, return value
</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 ("Before: {0}", _name);
String result= Outresultmethod (out _name);
Console.WriteLine ("After call: {0}", _name);
Console.WriteLine ("Return results: {0}", result);
Console.readkey ();
}
}
}
Run Result:
Out is used more in the actual project because out can return multiple values
Copy Code code as follows:
Class Program
{
<summary>
Out output value, return value
</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 ("Before: {0}", _name);
string result = Outresultmethod (out _name, out _password);//Multiple parameter passing
Console.WriteLine ("After call: {0}", _name);
Console.WriteLine ("Return results: {0}", result);
Console.readkey ();
}
}
Lenovo multiple parameters, you must have thought of the use of arrays, yes, the array is a good way, the array itself to the same type of parameters packaging "encapsulation" as an object passed to the method, which can simplify the writing of multiple parameter methods, but also to achieve similar overload effect.
Copy Code code as follows:
static void Outarraymethod (out string[] strarr)
{
int i = 0;
string[] _strarr = new STRING[10];
while (I < _strarr.length)
{
_strarr[i] = "The first" + i + "members";
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:
SOURCE download