下面我總結下我對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);
&