理解C#編程函數(shù)參數(shù)傳遞中out修飾符的作用
C#編程語言中,函數(shù)的返回值通常只能是一個。然而,使用out修飾符可以增加函數(shù)的返回值數(shù)量。在本文中,我們將探討out修飾符在函數(shù)參數(shù)傳遞中的作用。創(chuàng)建一個測試項目首先,我們需要打開Visual St
C#編程語言中,函數(shù)的返回值通常只能是一個。然而,使用out修飾符可以增加函數(shù)的返回值數(shù)量。在本文中,我們將探討out修飾符在函數(shù)參數(shù)傳遞中的作用。
創(chuàng)建一個測試項目
首先,我們需要打開Visual Studio 2015開發(fā)工具,并點擊菜單欄的"文件" -> "新建" -> "項目",然后選擇"控制臺應用程序"來創(chuàng)建一個新的控制臺項目,以便測試函數(shù)參數(shù)傳遞時out修飾符的作用。
代碼示例
在項目的入口文件Program.cs中,我們可以寫入以下代碼:
```C#
using System;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name;
int id;
bool b Test(name, id);
}
static bool Test(string name, int id)
{
name "張三";
id 1;
return true;
}
}
}
```
這里的Test函數(shù)接收兩個沒有使用out修飾符的變量參數(shù)name和id。在入口函數(shù)Main中聲明了這兩個變量,但沒有給它們賦值。
測試未使用out修飾符的情況
點擊運行按鈕,運行代碼會導致錯誤,因為在參數(shù)傳遞之前沒有對變量進行初始化,即沒有賦值操作。
使用out修飾符
為了解決上述問題,我們可以修改代碼,在參數(shù)傳遞時使用out修飾符。修改后的代碼如下:
```C#
using System;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name;
int id;
bool b Test(out name, out id);
();
}
static bool Test(out string name, out int id)
{
name "張三";
id 1;
return true;
}
}
}
```
再次點擊運行按鈕,運行代碼不會報錯了。也就是說,使用了out修飾符來傳遞參數(shù),不需要事先給變量賦值。
注意事項
實際上,即使我們在參數(shù)傳遞之前給變量賦值了,使用out修飾符的參數(shù)也必須在函數(shù)內(nèi)部重新賦值。例如,下面的代碼將導致錯誤:
```C#
using System;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name "李四";
int id 2;
bool b Test(out name, out id);
();
}
static bool Test(out string name, out int id)
{
// name "張三";
// id 1;
return true;
}
}
}
```
因此,在使用out修飾符的情況下,我們必須在函數(shù)內(nèi)部重新賦值。
使用out修飾符實現(xiàn)多返回值
通過測試代碼我們可以看到,使用out修飾符類似于實現(xiàn)多返回值的功能。我們可以打印出使用out修飾的變量。修改代碼如下:
```C#
using System;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name;
int id;
bool b Test(out name, out id);
Console.WriteLine(name);
Console.WriteLine(id);
Console.WriteLine(b);
();
}
static bool Test(out string name, out int id)
{
name "張三";
id 1;
return true;
}
}
}
```
點擊運行,成功打印出了兩個使用out修飾的參數(shù)和Test函數(shù)的返回值。這是out修飾符最常用的功能之一。