开发者

Make a c# / wpf event fire only once?

I have a case where I want a given event to execute once, and only once. I'm trying to do it this way, but I'm having prolems (else I wouldn't be asking). Note that the following code is inside the function that decides that the event needs to be fired.

EventHandler h = delegate(Object sender, EventArgs e) {
  FiringControl.TheEvent -= h; // <-- Error, use of unassigned local variable "h"
  // Do stuff
}
FiringControl.TheEvent += h;

In general this should work because of the way scope is preserved for deleg开发者_Python百科ates until after they're done running, but, since h is in the process of being built when I try to use it it is still considered to be "uninitialized", apparently.


You could set h = null first and then set it equal to something else? Like this?

EventHandler h = null;

h = delegate(Object sender, EventArgs e) {
  FiringControl.TheEvent -= h; // <-- Error, use of unassigned local variable "h"
  // Do stuff
}

FiringControl.TheEvent += h;

But are you sure this is the right approach? What are you trying to do overall?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜