问题描述:

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, MyEventArgs 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
                               };
相关阅读:
Top