开发者

How to simulate array of events in C#? (like in VB6)

I have an object with event handlers and I want to make something similar to VB6 to make array of that object. Something like:

MyHandler(object sender, MyEvent开发者_如何学JAVAArgs e, int IndexOfObject)


There are some minor caveats...you have to make sure that the variable you use to pass to the handler does not change within the scope. This is due to the fact that C# supports lexical closure and uses the variables by reference (I'm sure Jon Skeet could explain it better). Just copy the variables you use or you'll get some funny behavior.

for (int i = 0; i < observed.Length; ++i)
{
    int idx = i;
    observed[idx].WhateverEvent += delegate(object sender, EventArgs e)
                                   {
                                       MyHandler(sender, e, idx);
                                   };
}


observed[idx].WhateverEvent += delegate(sender, e)
{
    // Code that was in Myhandler, can access idx
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜