C#函数参数传送之out与ref的应用
下面我总结下我对out和ref引用参数的看法:1.out和ref引用参数的相同点:都是通过引用传递参数给函数;
2.out和ref引用参数的不同点是:用ref引用传递参数,该参数必须经过初始化,并且不能在调用它的函数中初始化,以下例子是错误的:
namespace refConsoleApp
{
class MyRefClass
{
static void MyRefMethod(ref int i)
{
int i=20;
}
static void main(string[] args)
{
int value; //not initialized the value;
MyRefMethod(ref value);
Console.WriteLine("The value is {0}",value);
}
}
}
3.使用out引用多个参数来返回多个值,这允许方法任意地返回需要的值,以下例子:
namespace multi_outConsoleApp
{
class MyMultipleoutClass
{
static void MyMultipleMethod(out int i, out string str1, out string str2)
{
i = 20;
str1 = "I was born";
str2 = "zhaoqing";
}
static void Main(string[] args)
{
int value;
string s1, s2;
MyMultipleMethod(out value,out s1,out s2);
Console.WriteLine("The integer value is {0} The first string value is {1} The second string value is {2}", value, s1, s2);
}
}
}
显示的结果为:
The integer value is 20
The first string value is I was born
The second string value is zhaoqing
4. 如果一个方法使用ref引用参数,另一个方法使用out引用参数,则这两个相同方法名的函数不能重载,否则出现编译错误,以下例子出现: " cannot define overloaded methods that differ only on ref and out "
namespace overloadofConsoleApp
{
class overloadofclass
{
static void MyMethod(ref int i)
{
i = 20;
}
static void MyMethod(out int i)
{
i = 40;
}
static void Main(string[] args)
{
int refvalue=0;
MyMethod(ref refvalue);
Console.WriteLine("The value is {0}", refvalue);
&nbs
补充:软件开发 , C# ,