c#中out、ref和params的用法与区别
ref和out都對(duì)函數(shù)參數(shù)采用引用傳遞形式——不管是值類型參數(shù)還是引用類型參數(shù),并且定義函數(shù)和調(diào)用函數(shù)時(shí)都必須顯示生命該參數(shù)為
ref/out形式。兩者都可以使函數(shù)傳回多個(gè)結(jié)果。
兩者區(qū)別:
兩種參數(shù)類型的設(shè)計(jì)思想不同,ref的目的在于將值類型參數(shù)當(dāng)作引用型參數(shù)傳遞到函數(shù),是函數(shù)的輸入?yún)?shù),并且在函數(shù)內(nèi)部的任何改變也
都將影響函數(shù)外部該參數(shù)的值;而out的目的在于獲取函數(shù)的返回值,是輸出參數(shù),由函數(shù)內(nèi)部計(jì)算得到的值再回傳到函數(shù)外部,因此必須在
函數(shù)內(nèi)部對(duì)該參數(shù)賦值,這將沖掉函數(shù)外部的任何賦值,使得函數(shù)外部賦值毫無意義。
表現(xiàn)為:
1、out必須在函數(shù)體內(nèi)初始化,這使得在外面初始化變得沒意義。也就是說,out型的參數(shù)在函數(shù)體內(nèi)不能得到外面?zhèn)鬟M(jìn)來的初始值。
2、ref必須在函數(shù)體外初始化。
3、兩者在函數(shù)體內(nèi)的任何修改都將影響到函數(shù)體外面。
例:
using System;
namespace ConsoleApplication1
{
class C
{
public static void reffun(ref string str)
{
str += " fun";
}
public static void outfun(out string str)
{
str = "test"; //必須在函數(shù)體內(nèi)初始, 如無此句,則下句無法執(zhí)行,報(bào)錯(cuò)
str += " fun";
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
string test1 = "test";
string test2; //沒有初始
C.reffun( ref test1 ); //正確
C.reffun( ref test2 ); //錯(cuò)誤,沒有賦值使用了test2
C.outfun( out test1 ); //正確,但值test無法傳進(jìn)去
C.outfun( out test2 ); //正確
Console.Read();
}
}
}
params 關(guān)鍵字可以指定在參數(shù)數(shù)目可變處采用參數(shù)的方法參數(shù)。
在方法聲明中的 params 關(guān)鍵字之后不允許任何其他參數(shù),并且在方法聲明中只允許一個(gè) params 關(guān)鍵字。
The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.
No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is
permitted in a method declaration.
// cs_params.cs
using System;
public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
static void Main()
{
UseParams(1, 2, 3);
UseParams2(1, 'a', "test");
// An array of objects can also be passed, as long as
// the array type matches the method being called.
int[] myarray = new int[3] {10,11,12};
UseParams(myarray);
}
}
Output
1
2
3
1
a
test
10
11
12
總結(jié)
以上是生活随笔為你收集整理的c#中out、ref和params的用法与区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 总结了C#中string.format用
- 下一篇: 集市中迷失的一代:FreeBSD核心开发