简介
变量和函数根据作用域,有本地的,如local variable, 也有全局的,如Global variable.
对于OO领域的函数,一般我们知道,根据访问限定,有public、protected、private;
其他的还有内联的inline的函数。
在C# 7中,类似内部类,函数也可以定义在一个函数体内,变成函数内的函数。C#称之为local function
。
示例
比如,微软的如下的示例:
public static IEnumerable<int> OddSequence(int start, int end)
{
if (start < 0 || start > 99)
throw new ArgumentOutOfRangeException("start must be between 0 and 99.");
if (end > 100)
throw new ArgumentOutOfRangeException("end must be less than or equal to 100.");
if (start >= end)
throw new ArgumentException("start must be less than end.");
return start%2 == 1?GetOddSequenceEnumerator():GetEvenSequenceEnumrator();
IEnumerable<int> GetOddSequenceEnumerator()
{
for (int i = start; i <= end; i++)
{
if (i % 2 == 1)
yield return i;
}
}
IEnumerable<int> GetEvenSequenceEnumrator()
{
for (int i = start; i <= end; i++)
{
if (i % 2 == 0)
yield return i;
}
}
}
在上面的示例中,定义了2个local function
.
定义及调用位置
local function
可以被调用和定义在这些地方:
- 构造器
- 属性访问子
- 事件访问子
- 匿名函数
- Lam不大表达式中
- Finalizers
- 另外的local function内。
定义格式:
<modifiers: async | unsafe> <return-type> <method-name> <parameter-list>