J
Joel
Here's a tricky one for all the .NET heads.
I have a base class B with a constructor and an initialization method:
public B()
{
Initiliaze();
}
private void Initialize()
{
//enumerate through a farily large list
}
I have a derived class D that implements the default constructor and would
like to do something to each item in the list that Initialize enumerates.
OK, let's add an event handler to B!
protected delegate void OnEnumHandler(object obj);
protectd event OnEnumHandler OnEnum;
then in Initialize for each item I iterate through I can do:
if(OnEnum!=null)
OnEnum(item);
The problem is my constructor in D looks like:
public D() : base()
{
this.OnEnum+=new OnEnumHandler(My_OnEnum);
}
Now D's My_OnEnum will get called, right? Wrong. Because my base constructor
gets called before I have a chance to add my event handler.
So then I thought, just pass in the event handler as part of the base
constructor, e.g.: protected B(OnEnumHandler). Well, B compiles fine but
when in D when I do
protected D() : base(new OnEnumHandler(OnEnum))
it chokes with "An object reference is required for the nonstatic field,
method, or property 'My_OnEnum(object)'" because my object doesn't have life
yet.
I'm stumped. Any ideas? TIA
</joel>
I have a base class B with a constructor and an initialization method:
public B()
{
Initiliaze();
}
private void Initialize()
{
//enumerate through a farily large list
}
I have a derived class D that implements the default constructor and would
like to do something to each item in the list that Initialize enumerates.
OK, let's add an event handler to B!
protected delegate void OnEnumHandler(object obj);
protectd event OnEnumHandler OnEnum;
then in Initialize for each item I iterate through I can do:
if(OnEnum!=null)
OnEnum(item);
The problem is my constructor in D looks like:
public D() : base()
{
this.OnEnum+=new OnEnumHandler(My_OnEnum);
}
Now D's My_OnEnum will get called, right? Wrong. Because my base constructor
gets called before I have a chance to add my event handler.
So then I thought, just pass in the event handler as part of the base
constructor, e.g.: protected B(OnEnumHandler). Well, B compiles fine but
when in D when I do
protected D() : base(new OnEnumHandler(OnEnum))
it chokes with "An object reference is required for the nonstatic field,
method, or property 'My_OnEnum(object)'" because my object doesn't have life
yet.
I'm stumped. Any ideas? TIA
</joel>