C# ref and out的使用小結(jié)
相同點(diǎn):
1. ref 和 out 都是按地址傳遞的,使用后都將改變?cè)瓉韰?shù)的數(shù)值;
2. 方法定義和調(diào)用方法都必須顯式使用 ref 或者 out關(guān)鍵字;
3. 通過ref 和 ref 特性,一定程度上解決了C#中的函數(shù)只能有一個(gè)返回值的問題。
不同點(diǎn):
傳遞到 ref 參數(shù)的參數(shù)必須初始化,否則程序會(huì)報(bào)錯(cuò)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
Fun(ref a,ref b);
Console.WriteLine("a:{0},b:{1}", a, b);//輸出:3和4說明傳入Fun方法是a和b的引用
}
static void Fun(ref int a, ref int b) {
a = 3;
b = 4;
}
}
}
out關(guān)鍵字無法將參數(shù)值傳遞到out參數(shù)所在的方法中, out參數(shù)的參數(shù)值初始化必須在其方法內(nèi)進(jìn)行,否則程序會(huì)報(bào)錯(cuò)。
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int a = 100;
int b;
Fun(out a, out b);
Console.WriteLine("a:{0},b:{1}", a, b);
}
static void Fun(out int a, out int b)
{
//a = 1+2;
if (a == 100)
a = 2;
b = 1;
}
}
}
代碼里報(bào)錯(cuò) “Use of unassigned out parameter 'a' ”
下面的代碼是正確的。
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int a = 100;
int b;
Fun(out a, out b);
Console.WriteLine("a:{0},b:{1}", a, b);
}
static void Fun(out int a, out int b)
{
a = 1+2;
b = 1;
}
}
}
輸出結(jié)果為:

注意點(diǎn):
using System;
namespace ConsoleApplication1
{
class Program
{
public void SampleMethod(ref int i) { }
public void SampleMethod(out int i) { }
}
}
上面代碼會(huì)報(bào)錯(cuò)“ 'Program' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' ”
盡管 ref 和 out 在運(yùn)行時(shí)的處理方式不同,但在編譯時(shí)的處理方式相同。因此,如果一個(gè)方法采用 ref 參數(shù),而另一個(gè)方法采用 out 參數(shù),則無法重載這兩個(gè)方法。例如,從編譯的角度來看,以下代碼中的兩個(gè)方法是完全相同的,因此將不會(huì)編譯上面的代碼。
using System;
namespace ConsoleApplication1
{
class Program
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
}
上面代碼會(huì)報(bào)錯(cuò)“ 'Program' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' ”
盡管 ref 和 out 在運(yùn)行時(shí)的處理方式不同,但在編譯時(shí)的處理方式相同。因此,如果一個(gè)方法采用 ref 參數(shù),而另一個(gè)方法采用 out 參數(shù),則無法重載這兩個(gè)方法。例如,從編譯的角度來看,以下代碼中的兩個(gè)方法是完全相同的,因此將不會(huì)編譯上面的代碼。
using System;
namespace ConsoleApplication1
{
class Program
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
}
但是,如果一個(gè)方法采用 ref 或 out 參數(shù),而另一個(gè)方法不采用這兩個(gè)參數(shù),則可以進(jìn)行重載。
以上就是C# ref and out的使用小結(jié)的詳細(xì)內(nèi)容,更多關(guān)于C# ref and out的使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#中事務(wù)處理和非事務(wù)處理方法實(shí)例分析
這篇文章主要介紹了C#中事務(wù)處理和非事務(wù)處理方法,較為詳細(xì)的分析了C#中事務(wù)處理與非事務(wù)處理的使用技巧,對(duì)于使用C#進(jìn)行數(shù)據(jù)庫程序開發(fā)有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
C#中實(shí)現(xiàn)查找字符串中指定字符位置方法小結(jié)
這篇文章主要為大家介紹了C#中實(shí)現(xiàn)查找字符串中指定字符位置的常用方法,本文將以"."字符為例,詳細(xì)講解這些方法的具體使用,需要的可以參考下2024-02-02
Unity Shader實(shí)現(xiàn)水波紋效果
這篇文章主要為大家詳細(xì)介紹了Unity Shader實(shí)現(xiàn)水波紋效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05

