C# 的本地函数

发布日期:2026-07-14 02:29:03   来源 : 杭州电子商务研究院    浏览量 :16
杭州电子商务研究院 发布日期:2026-07-14 02:29:03  
16

介绍

从 7.0 版开始,本地函数成为 C# 的一部分。其理念是在另一个函数中定义一个函数,类似于 Python 装饰器。另一种解释是,本地函数是函数的私有函数,其范围仅限于定义它的函数。

本地函数类似于匿名方法。有时,没有必要创建命名函数来执行特定操作,因为功能仅限于特定函数,而命名函数只会污染外部作用域。

我们将在本指南中了解有关局部函数的更多信息并研究几个用例。

本地函数

本地函数的类型与容器函数的类型相似;但是,编译器方面没有严格的规则或强制要求。当您有本地函数时,您可以使用 asyncunsafe修饰符

您不能在表达式体成员中定义本地函数。本地函数的目的是使您的程序更具可读性,并且由于您无法直接调用本地函数,因此可以防止您错误地调用它。您不能在本地函数中使用 static 关键字,并且您不能将属性应用于本地函数或其参数或参数类型之一。

局部函数常见的定义位置:

  1. 方法
  2. 构造函数
  3. 属性访问器
  4. 事件访问器
  5. Lambda 表达式
  6. 终结器,又称析构函数
  7. 局部函数(意味着局部函数可以相互嵌套)

局部函数的一个有用功能是它们允许立即出现异常。例如,当您使用迭代器时,只有在枚举异常时才会出现异常。

简单本地函数

让我们演示一个简单的本地功能。

      using System;

namespace loca
{   
    class LocalFunctions
    {
        static void Main(string[] args)
            {
            void Message(string say) {
                Console.WriteLine($"The message says: {say}");
            }
            Message("Welcome");
            Message("to");
            Message("the");
            Message("Written");
            Message("Guides");
            Console.ReadKey();
            }
    }
}
    

调用代码会给我们以下输出。

      The message says: Welcome
The message says: to
The message says: the
The message says: Written
The message says: Guides
    

这是最简单的本地函数形式。函数Message接受一个字符串并将消息输出到控制台。

此代码演示了本地函数如何从不同范围访问变量。

      using System;

namespace loca
{   
    class LocalFunctions
    {
        static void Main(string[] args)
            {
            int k = 10;
            double j = 99.9;
            void Scope(string x, int y) {
                Console.WriteLine($"The value of {nameof(x)} is {x}");
                Console.WriteLine($"The value of {nameof(y)} is {y}");
                Console.WriteLine($"The value of {nameof(k)} is {j}");
                Console.WriteLine($"The value of {nameof(j)} is {j}");
            }
            Scope("twelve", 666);
            Console.ReadKey();
            }
    }
}
    

输出应如下所示。

      The value of x is twelve
The value of y is 666
The value of k is 99.9
The value of j is 99.9
    

该函数可以访问名为kj的局部变量,因为它们是在容器函数内部定义的。

通用局部函数

让我们创建一个通用的本地函数。

      using System;

namespace loca
{   
    class LocalFunctions
    {
        static void Main(string[] args)
            {
            void MyGeneric<Value>(Value x) {
                Console.WriteLine($"Value from generic message: {x}");
            }
            MyGeneric<string>("twelve");
            MyGeneric<int>(2012);
            Console.ReadKey();
            }
    }
}
    

输出结果如下:

      Value from generic message: twelve
Value from generic message: 2012
    

泛型函数兼具可重用性、类型安全性和效率。它们通常与集合和对其执行操作的方法一起使用。

您还可以在在同一范围内声明的本地函数中引用out参数。让我们看看如何操作。

      using System;

namespace loca
{   
    class LocalFunctions
    {
        static void Main(string[] args)
            {
            void MyOut(string x, out string s) {
                s = $"Value from generic message: {x}";
            }
            string message = null;
            MyOut("twelve", out message);
            Console.WriteLine($"The value of out message: {message}");
            Console.ReadKey();
            }
    }
}
    

函数调用的输出如下:

      The value of out message: Value from generic message: twelve
    

输出消息变量捕获消息并与函数的输出字符串参数协同工作。

使用参数

最后我们检查一下params的用法。此关键字允许方法或函数采用可变数量的参数。

      using System;

namespace loca
{   
    class LocalFunctions
    {
        static void Main(string[] args)
            {
            void MyParams(params int[] array) {
                foreach (int element in array) {
                    Console.WriteLine($"Got the number of from the pipeline: {element}");
                }
            }
            int[] testArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            MyParams(testArray);
            Console.ReadKey();
            }
    }
}
    

这将产生以下输出。

      Got the number of from the pipeline: 1
Got the number of from the pipeline: 2
Got the number of from the pipeline: 3
Got the number of from the pipeline: 4
Got the number of from the pipeline: 5
Got the number of from the pipeline: 6
Got the number of from the pipeline: 7
Got the number of from the pipeline: 8
Got the number of from the pipeline: 9
Got the number of from the pipeline: 10
    

结论

在本指南中,我们检查了 C# 中本地函数的用例。从演示应用程序中,我们看到了该语言引入了多少功能,以及它如何为开发人员以更高效的方式重组应用程序开辟了新的可能性。我希望这对您有所帮助,并且您找到了想要的东西。如果您喜欢它,请点赞。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据