C#:传递参数到回调 [英] C#: passing parameters to callbacks

查看:251
本文介绍了C#:传递参数到回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当通用的类(Record),我已经添加了一个回调处理程序,所以我可以做如下。

I have a fairly generic class (Record) that I have added a callback handler to, so I can do something like the following.

record.Save(AfterSaveMethod);

这也返回创建的记录的标识号。我现在的问题是,我有一个循环中的嵌套保存例程,我需要使用/传递 i 变量!

Which also returns the identity number of the record created. The issue I have now is that I have this nested save routine in a loop, and I need to use/pass the i variable!

for (int i; i < count ;i++)
{
    record.Save(AfterSaveMethod2) //but I need to pass i through as well
}  

这里?

A \重写保存方法并将其包含在此类(yuk)中,

A\ rewrite the save method and include it in this class (yuk),

B \\有一个重载的保存选项,它接受一个对象作为参数,所以我可以将它传递到我的记录类,然后与身份号码合并。返回的身份号码和任何额外包含在传递通过对象(嗯,听起来有点凌乱),

B\ have an overloaded save option that takes an object as a parameter, so I can pass it through to my record class, and then merge it with the identity number. Returning both the identity number and anything extra contained in the passed through object (hmm, sounds a bit messy),

C \有没有更性的选择? >

C\ is there a sexier option?

推荐答案

这是匿名方法或lambda表达式真正方便的地方:)

This is where anonymous methods or lambda expressions are really handy :)

尝试这个(假设为C#3):

Try this (assuming C# 3):

for (int i = 0; i < count; i++)
{
    int index = i;
    record.Save(id => AfterSaveMethod2(id, index));
}

注意这里的lambda表达式是捕获 / code>,而不是 i - 这是为了避免关闭循环变量

Note that the lambda expression here is capturing index, not i - that's to avoid the problems inherent in closing over the loop variable.

这篇关于C#:传递参数到回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆