0

So I've the following scenario:

class A
{
  public event MyEventHandler MyEvent;
}

abstract class B : MarshalByRefObject
{
  public event MyEventHandler MySecondEvent;
  private A subClass;
}

Now what I'd like to achieve is, Class B, MySecondEvent to basically combine event MyEvent from Class A, so when A event hits, B does as well.

I know I could achieve that subscribing via constructor but that's not an option here. And the inherited class also can't access base class's subClass.

What would be the best solution in such case? Thanks!

Alex Maher
  • 83
  • 2
  • 6
  • @Jerry Hey Jerry no, only first event should ever be fired, for second one to do so as well, I just basically want a chain which is quite simple to do, but in such scenario not really. – Alex Maher Mar 10 '19 at 17:54
  • If B inherits A, then why not just subscribe to A's event and not have one in B. I'm having troubles trying to figure out what you're trying to accomplish here. – Jerry Mar 10 '19 at 17:55
  • @Jerry Maybe I should've included more code, but basically because of Remoting. Class A is instantiated as a proxy class, and B is a Plugin custom class inheriting B. subClass A is set dynamically using reflection when assembly inheriting B is loaded. Makes more sense? – Alex Maher Mar 10 '19 at 17:58

1 Answers1

1

Since you're using reflection anyways, I would use it to chain invoke the event.

This is a modified form of the answer https://stackoverflow.com/a/586156/6824955

class A
{
    public event EventHandler MyEvent;
}

abstract class B : MarshalByRefObject
{
    public B()
    {
        MySecondEvent += InvokeSubClass;
    }

    private void InvokeSubClass(object o, EventArgs e)
    {
        var eventDelegate = (MulticastDelegate)subClass.GetType()
            .GetField("MyEvent", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
            .GetValue(subClass);

        if (eventDelegate != null)
        {
            foreach (var handler in eventDelegate.GetInvocationList())
            {
                handler.Method.Invoke(handler.Target, new object[] { subClass, e });
            }
        }
    }

    public event EventHandler MySecondEvent;
    private A subClass;
}
Jerry
  • 1,477
  • 7
  • 14