C# ref and out的使用小結(jié)
相同點:
1. ref 和 out 都是按地址傳遞的,使用后都將改變原來參數(shù)的數(shù)值;
2. 方法定義和調(diào)用方法都必須顯式使用 ref 或者 out關(guān)鍵字;
3. 通過ref 和 ref 特性,一定程度上解決了C#中的函數(shù)只能有一個返回值的問題。
不同點:
傳遞到 ref 參數(shù)的參數(shù)必須初始化,否則程序會報錯。
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)進行,否則程序會報錯。
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;
}
}
}
代碼里報錯 “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é)果為:

注意點:
using System;
namespace ConsoleApplication1
{
class Program
{
public void SampleMethod(ref int i) { }
public void SampleMethod(out int i) { }
}
}
上面代碼會報錯“ 'Program' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' ”
盡管 ref 和 out 在運行時的處理方式不同,但在編譯時的處理方式相同。因此,如果一個方法采用 ref 參數(shù),而另一個方法采用 out 參數(shù),則無法重載這兩個方法。例如,從編譯的角度來看,以下代碼中的兩個方法是完全相同的,因此將不會編譯上面的代碼。
using System;
namespace ConsoleApplication1
{
class Program
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
}
上面代碼會報錯“ 'Program' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' ”
盡管 ref 和 out 在運行時的處理方式不同,但在編譯時的處理方式相同。因此,如果一個方法采用 ref 參數(shù),而另一個方法采用 out 參數(shù),則無法重載這兩個方法。例如,從編譯的角度來看,以下代碼中的兩個方法是完全相同的,因此將不會編譯上面的代碼。
using System;
namespace ConsoleApplication1
{
class Program
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
}
但是,如果一個方法采用 ref 或 out 參數(shù),而另一個方法不采用這兩個參數(shù),則可以進行重載。
以上就是C# ref and out的使用小結(jié)的詳細內(nèi)容,更多關(guān)于C# ref and out的使用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#中實現(xiàn)查找字符串中指定字符位置方法小結(jié)
這篇文章主要為大家介紹了C#中實現(xiàn)查找字符串中指定字符位置的常用方法,本文將以"."字符為例,詳細講解這些方法的具體使用,需要的可以參考下2024-02-02

