首頁  >  文章  >  後端開發  >  C# 局部函數

C# 局部函數

PHPz
PHPz原創
2024-09-03 15:14:58771瀏覽

在另一個函數體內的函數是私有的,其範圍僅限於創建它的函數,在C# 中稱為本地函數,使用它可以在另一個方法體內聲明一個方法,該方法是已經定義,並且此本地函數功能是在C# 版本7.0 中在C# 中引入的。並且在另一個函數體內創建的函數的類型與創建該函數的函數的類型相同,並且此類局部函數可以由其容器的成員調用,並且允許創建多個局部函數但不允許在局部函數中使用static關鍵字。

文法:

文法如下:

<modifiers: async | unsafe> <return-type> <method-name> <parameter-list>
  • 其中 async 和 unsafe 是可以與本地方法一起使用的修飾符。
  • 傳回型別是方法傳回值的型別。
  • 方法名稱是賦予方法的名稱。
  • 參數清單是可以傳遞給方法的參數清單。

C# 中局部函數的工作

  • 局部函數是私有函數,可以在另一個函數體內聲明,而此類局部函數的範圍僅限於創建它的函數。
  • 本地函數可以從終結器、lambda 表達式、屬性評估器、建構子等呼叫。
  • 局部函數中不能使用存取修飾符和 static 關鍵字,甚至修飾符 private 也是如此,因為局部函數預設是私有的。
  • 在容器方法內部定義並包含方法參數的局部變數可以使用局部函數存取。
  • 屬性不能應用於局部函數或其參數和參數類型。
  • 修飾符 unsafe 和 async 可以與本地函數一起使用。

範例

下面給出的是提到的例子:

範例#1

C# 程序,示範程序中將兩個數字相加的本地函數。

代碼:

using System;
//a class called check is defined
namespace LocalFunction
{
public class Program
{
// Main method is called
public static void Main(string[] args)
{
// the local methods are being called within the main method
int res = Addition(100, 200);
Console.WriteLine("The addition result of adding 100 and 200 is: {0}", +res);
//local method is created
int Addition(int x, int y)
{
return x + y;
}
}
}
}

輸出:

C# 局部函數

在上面的程式中,定義了一個名為check的類別。然後呼叫 main 方法,其中定義了本機方法。然後呼叫在 main 方法中建立的本機方法,並將要相加的兩個數字作為參數傳遞給本機方法。

範例#2

用於示範程式中本機函數的 C# 程式。

代碼:

using System;
//a class called program is called
namespace LocalFunction
{
public class Program
{
//main method is called
public static void Main(string[] args)
{
//Local Function is created
int Function(int x)
{
return 100 * x;
}
//Calling the local function within the main method
Console.WriteLine("The product after performing the operation is: {0}",Function(10));
}
}
}

輸出:

C# 局部函數

在上面的程式中,定義了一個名為program的類別。然後呼叫 main 方法,其中定義了本地方法,該方法用於查找數字與 100 相乘後的乘積,並作為參數傳遞。然後呼叫在 main 方法中建立的本地方法,並使用一個數字來呼叫該數字,該數字與 100 相乘後的乘積作為參數傳遞給本地方法。

範例#3

C# 程序,用於示範程序中求數字平方的局部函數。

代碼:

using System;
//a class called program is called
namespace LocalFunction
{
public class Program
{
//main method is called
public static void Main(string[] args)
{
//Local Function is created
int Square(int x)
{
return x * x;
}
//Calling the local function within the main method
Console.WriteLine("The square after performing the operation is: {0}",Square(10));
}
}
}

輸出:

C# 局部函數

在上面的程式中,定義了一個名為program的類別。然後呼叫 main 方法,其中定義了查找作為參數傳遞的數字的平方的本機方法。然後呼叫在 main 方法中建立的本機方法,並使用一個要求平方的數字作為參數傳遞給本機方法。

以上是C# 局部函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:C# 匿名函數下一篇:C# 匿名函數