在方法参考文档中,有一些示例代码,复制如下:
char8 GetNext()
{
if (i >= str.Length)
return 0;
return str[i++];
}
/* Allocates a delegate bound to GetNext() */
delegate char8() strDlg = scope => GetNext;
strDlg = scope () =>
{
return 'A';
};
strDlg = scope [&] () =>
{
return GetNext();
};
/* This delegate owns a string */
String tempStr = new String(str);
tempStr.EnsureNullTerminated();
strDlg = scope [&] () =>
{
return str[i++];
}
~
{
delete tempStr;
};
在 lambda 定义的三个示例中的两个示例中,[&]
分配表达式 ( scope
) 和 lambda 的参数之间有一个。那是什么[&]
?
对于其他示例,以下是IDE 源代码中包含的测试的一些摘录:
struct Splattable
{
public int32 mA = 10;
public int16 mB = 200;
public void TestLambda() mut
{
delegate int(ref int a, ref int b) dlg = scope [&] (a, b) =>
{
a += 20;
b += 30;
mA++;
return mA + a + b;
};
mA = 100;
int testA = 8;
int testB = 9;
Test.Assert(dlg(ref testA, ref testB) == 100+1 + 20+8 + 30+9);
Test.Assert(testA == 28);
Test.Assert(testB == 39);
Test.Assert(mA == 101);
}
}
class ClassA
{
public int mA;
public void TestLambda()
{
delegate int(ref int a, ref int b) dlg = scope (a, b) =>
{
a += 20;
b += 30;
mA++;
return mA + a + b;
};
mA = 100;
int testA = 8;
int testB = 9;
Test.Assert(dlg(ref testA, ref testB) == 100+1 + 20+8 + 30+9);
Test.Assert(testA == 28);
Test.Assert(testB == 39);
Test.Assert(mA == 101);
}
}
这是源代码的 IDEHelper 部分的另一组示例/测试,其中每个 lambda 定义都有[&]
:
using System;
namespace Tests
{
class Lambdas
{
[Test]
static void TestBasics()
{
int a = 1;
Action act = scope [&] () =>
{
Action act2 = scope [&] () =>
{
a += 100;
};
act2();
};
act();
Test.Assert(a == 101);
}
static int Add3<T>(T func) where T : delegate int()
{
return func() + func() + func();
}
[Test]
static void TestValueless()
{
Test.Assert(Add3(() => 100) == 300);
int a = 20;
int result = Add3(() => a++);
Test.Assert(result == 63);
}
[Test]
static void LambdaWithDtor()
{
int a = 10;
int b = 20;
//
{
delegate void() dlg = scope [&] () =>
{
a++;
}
~
{
b++;
};
dlg();
}
Test.Assert(a == 11);
Test.Assert(b == 21);
delegate void() dlg = new [&] () =>
{
a += 100;
}
~
{
b += 200;
};
dlg();
Test.Assert(a == 111);
Test.Assert(b == 21);
delete dlg;
Test.Assert(b == 221);
}
}
}
最后,[&]
严格来说可能不是 lambda 的东西。我可以将它放在其他定义中let s = new [&] String();
,例如它可以毫无问题地编译,并且据我所知,运行结果与没有它时的结果相同。但是,我还没有看到它出现在示例/测试代码的其他任何地方。