- 結(jié)論
先上結(jié)論,答案是yes,C#中數(shù)組確實具有out參數(shù)的特性。
- 疑問
最近開發(fā)一個上位機(jī)的功能,有段代碼看得我一直很迷糊,我的認(rèn)識,函數(shù)的執(zhí)行結(jié)果,要么在函數(shù)中通過return返回,要么通過out或ref參數(shù)返回。這段代碼中明顯沒有通過return獲取返回值,輸入?yún)?shù)倒是看起來很像out返回值,但是我反復(fù)確認(rèn)了N遍,定義就是沒有out或ref類型。這就很是疑惑了,只好先放一邊,先把它當(dāng)做out參數(shù)取返回值理解去完成開發(fā),今天有空終于把這個疑問摸清楚了。
- 驗證
各種百度,網(wǎng)上并沒有答案。于是參照原來的代碼寫了一段Console程序,發(fā)現(xiàn)輸入?yún)?shù)(字節(jié)數(shù)組)還真是在函數(shù)中更改后返回最新值了。此時原先的不明就里已經(jīng)確定為就是【字節(jié)數(shù)組】的原因了,最初懷疑是Byte類型的原因,在程序中驗證后發(fā)現(xiàn)并不是,然后用非字節(jié)類型的數(shù)組驗證了下,仍然能在實參中取到函數(shù)更新后的值,確定為就是數(shù)組的原因。此時已經(jīng)有點懷疑引用類型值類型的原因了,但是不對啊,平時引用類型string用的這么多,印象中并不會返回值啊,通過程序驗證,也確定string參數(shù)沒有out參數(shù)的特性,這就不得其解了。。直到搜到一篇文章,說string類型是一種特殊的引用類型,其實此處就等于是值傳遞,所有的謎團(tuán)才清晰了。原因就在于參數(shù)分傳值與傳址兩種,數(shù)組為引用類型,是按地址傳遞的,所以具備out參數(shù)的特性。
點擊查看代碼
class Pr
{
private static byte[] m_byBuff = new byte[2048];
static void Main(string[] args)
{
byte[] barr_read = new byte[1024];
int int_read = 0;
byte byte_read=0;
int[] iarr_read = new int[10];
string str_read = "0";
bool r = DataProcess(barr_read);
bool r1 = DataProcess(int_read);
bool r2 = DataProcess(byte_read);
bool r3 = DataProcess(str_read);
//向控制臺輸出
System.Console.WriteLine("數(shù)組類型實參傳參后值(傳參前為0,傳參函數(shù)中有賦值):");
System.Console.WriteLine("arr[0]:{0}",barr_read[0].ToString());
System.Console.WriteLine("arr[1]:{0}", barr_read[1].ToString());
System.Console.WriteLine("arr[2]:{0}", barr_read[2].ToString());
System.Console.WriteLine("arr[3]:{0}", barr_read[3].ToString());
System.Console.WriteLine("int類型實參傳參后值(傳參前為0,傳參函數(shù)中有賦值):");
System.Console.WriteLine(int_read.ToString());
System.Console.WriteLine("byte類型實參傳參后值(傳參前為0,傳參函數(shù)中有賦值):");
System.Console.WriteLine(byte_read.ToString());
System.Console.WriteLine("string類型實參傳參后值(傳參前為‘0’,傳參函數(shù)中有賦值):");
System.Console.WriteLine(str_read);
}
//Main是static的,因此aa也要申明為static,否則無法訪問
private static bool DataProcess(byte[] outbuff)
{
outbuff[0] = (byte)1;
outbuff[1] = (byte)2;
outbuff[2] = (byte)3;
outbuff[3] = (byte)4;
return true;
}
private static bool DataProcess(int[] outbuff)
{
outbuff[0] = 11;
outbuff[1] = 12;
outbuff[2] = 13;
outbuff[3] = 14;
return true;
}
private static bool DataProcess(int outbuff)
{
outbuff=10;
return true;
}
private static bool DataProcess(byte outbuff)
{
outbuff = 20;
return true;
}
private static bool DataProcess(string outbuff)
{
outbuff = "30";;
return true;
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-537532.html
- 參考
https://blog.csdn.net/weixin_44806070/article/details/107882525
https://www.cnblogs.com/mdnx/archive/2012/09/04/2671060.html文章來源地址http://www.zghlxwxcb.cn/news/detail-537532.html
到了這里,關(guān)于C#中數(shù)組參數(shù)=out參數(shù)?的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!