如何用c#lambda语法编写以下回调延续?
我正在编写一个异步单元测试,我想使用lambdas(或匿名方法?)将它串在一起,这样就不必为continuations定义命名函数 我读过几篇关于lambdas的文章,但是对于我不感兴趣的每种风格的构造,我都会处理 我想做如下事情(摘自): 但我想我不需要排队回调()之类的东西 以下是我不带lambdas的代码:如何用c#lambda语法编写以下回调延续?,c#,lambda,C#,Lambda,我正在编写一个异步单元测试,我想使用lambdas(或匿名方法?)将它串在一起,这样就不必为continuations定义命名函数 我读过几篇关于lambdas的文章,但是对于我不感兴趣的每种风格的构造,我都会处理 我想做如下事情(摘自): 但我想我不需要排队回调()之类的东西 以下是我不带lambdas的代码: [TestClass] public class IdentityEditDatabaseTest : WorkItemTest { [TestMethod, Asynchrono
[TestClass]
public class IdentityEditDatabaseTest : WorkItemTest
{
[TestMethod, Asynchronous] public void testNullInsert()
{
wipeTestData(testNullInsertContinue1);
}
private void testNullInsertContinue1(String errorString)
{
IdentityProperties properties = new IdentityProperties(getContext());
properties.setUserName(DATABASE_TEST);
postUserEdit(properties, testNullInsertContinue2);
}
private void testNullInsertContinue2(String errorString)
{
Assert.assertTrue(errorString == null);
wipeTestData(testNullInsertContinue3);
}
private void testNullInsertContinue3(String errorString)
{
TestComplete();
}
}
...
问题是:
如何使用lambdas(或匿名方法?)将上述内容串在一起,这样就不必为continuations定义命名函数了?
请尽可能多地解释新的语法,因为我仍在努力理解这个概念
非常感谢 如果我们采用以下方法:
private void DoSomething(object argument)
{
// Do something with the argument here
}
您可能知道,它可以分配给委托变量,如下所示:
Action<object> asDelegate = DoSomething;
[TestMethod, Asynchronous]
public void testNullInsert()
{
wipeTestData((string errorString) =>
{
IdentityProperties properties = new IdentityProperties(getContext());
properties.setUserName(DATABASE_TEST);
postUserEdit(properties, testNullInsertContinue2);
});
}
我在这里所做的只是将名称testNullInsertContinue1替换为包含相同功能的lambda表达式。如果需要,也可以对testNullInsertContinue2执行相同的操作
一旦您更加熟悉lambda表达式的使用,您可以删除诸如参数周围的括号(如果只有一个参数)和参数类型之类的内容,因为编译器通常可以推断它们,但我这样写是为了尽可能让您了解发生了什么。希望这有帮助。如果我们有以下方法:
private void DoSomething(object argument)
{
// Do something with the argument here
}
您可能知道,它可以分配给委托变量,如下所示:
Action<object> asDelegate = DoSomething;
[TestMethod, Asynchronous]
public void testNullInsert()
{
wipeTestData((string errorString) =>
{
IdentityProperties properties = new IdentityProperties(getContext());
properties.setUserName(DATABASE_TEST);
postUserEdit(properties, testNullInsertContinue2);
});
}
我在这里所做的只是将名称testNullInsertContinue1替换为包含相同功能的lambda表达式。如果需要,也可以对testNullInsertContinue2执行相同的操作
一旦您更加熟悉lambda表达式的使用,您可以删除诸如参数周围的括号(如果只有一个参数)和参数类型之类的内容,因为编译器通常可以推断它们,但我这样写是为了尽可能让您了解发生了什么。希望这能有所帮助。我可能非常愚蠢,可能我不理解这个问题(看起来很难),但你为什么不订阅timer.Tick事件?我可能非常愚蠢,可能我不理解这个问题(看起来很难),但你为什么不订阅timer.Tick事件?谢谢,这完美地回答了我的问题。不幸的是,我不能使用这种方法,因为这意味着每次我链接lambda时都需要重命名变量“errorString”,以避免CS0136:(谢谢,这完美地回答了我的问题。不幸的是,我不能使用这种方法,因为这意味着我需要重命名变量“errorString”每次我将lambda链起来以避免CS0136:(