3
public Class A
{

   public A()
   {
     someotherclass.someevent += new EventHandler(HandleEvent);
   }

   private void HandleEvent(object sender,CustomEventArgs e) 
   {
      if(e.Name == "Type1")
           Method1();
      else if(e.Name == "Type2")
           Method2();
   }

   protected virtual void Method1(){}
   protected virtual void Method2(){}
}

public class B: A
{
   public B()
   { /*Something*/}

   protected override void Method1(){/*some logic*/}
   protected override void Method2(){/*some other logic*/}
}

public class C: A
{
   public C()
   { /*Something*/}

   protected override void Method1(){/*some logic*/}
   protected override void Method2(){/*some other logic*/}
}

public class Main
{
    private A;

    public Main(){/*Something*/}

    private void StartB()
    {
       A = new B();
    } 

    private void StartC()
    {
       A = new C();
    } 
}

现在,发生的情况是,在我经历了一个调用StartB(第一个调用)和StartC(第二个调用)方法的循环之后,当触发someevent时,代码尝试执行Class B中的方法(以及稍后我希望是 C 类。我无法到达那里,因为它在调用 B 类中的方法时出错),而不是我希望它只调用C 类中的方法。

我认为,由于事件是在构造函数中订阅的,因此 B 类方法仍然会被触发,因为它最初是在调用 StartB 时订阅的。

Question:
I want only the methods of the class that is instantiated the latest should be executed.

For Example: if StartB and StartC are called in order, when someevent is triggered the Methods in Class C should only get executed. Same Vice-Versa. How to do that?

I know am doing something terribly wrong. Any help is much appreciated.

4

2 回答 2

3

You aren't unsubscribing from the event from your first instance so it will be called. If you don't want it to be called you need to unsubscribe. You could do something like this

class A
{

private static EventHandler lastHandler;

public A()
{
    //warning, not thread safe
    if(lastHandler != null)
    {
        someotherclass.someevent -= lastHandler;
    }
    lastHandler = new EventHandler(HandleEvent);
    someotherclass.someevent += lastHandler;
}

but it seems pretty hacky. You are probably better off implementing a method (e.g. IDisposable) to clean up your last instance before a creating a new one.

于 2011-11-17T09:01:13.000 回答
1

If I understand you correctly you are saying the methods on B are being called after startC is called and you don't wish this to happen?

I'm guessing your issue is that someotherclass is a static class, or an instance is somehow being shared between all the created B's and C's - in which case you need to unregister the old event handler from someotherclass.someevent when you create the new class. If you don't unregister the handler then the someotherclass object will have a reference to the B or C object that registered with it, so even though you are overwriting the reference in the main class the object is still kept alive by the reference in the event and is still being called when the event is triggered.

于 2011-11-17T09:02:01.800 回答