C #: cannot access parent class events?

never encountered this before. Here's a sample:

using System;

namespace Testing
{
    public class Test
    {
        public event Action ActionRequired;
    }

    public class ChildTest : Test
    {
        public void DoSomething()
        {
            if (this.ActionRequired != null)
                this.ActionRequired();
        }
    }
}

This will not work, the error is that I can only access the event from the base class.

It’s not difficult to sail (add a protected method to the base class that checks the event call and calls this method from the child classes), but I'm really curious what the idea of ​​this restriction is?

Greetings

Sebi

+5
source share
3 answers

You cannot call events from outside the class in which they were defined. However, you do not need to; just follow the idiomatic expression, also declaring a protected method to trigger the specified event.

class Whatever
{
    public event EventHandler Foo;

    protected virtual void OnFoo( EventArgs e )
    {
        EventHandler del = Foo;
        if( del != null )
        {
            del( this, e );
        }
    }
}

"Whatever" , OnFoo() EventArgs.

EDIT: , , ( , , ):

, . ( ) , . . , .

+13

, , - :

private Action _actionRequired;
public event Action ActionRequired
{
    add { _actionRequired += value; }
    remove { _actionRequired -= value }
}

( , )

, _actionRequired . , add/remove ( ). , , , - . , , , , . ActionRequired , , .

, . , .

+3

, @ThomasLevesque fooobar.com/questions/1063423/...

. :

 public class Test
 {
    protected Action _actionRequired;
    public event Action ActionRequired {
        add {
            _actionRequired += value;
        }
        remove {
            _actionRequired += value;
        }
    }
 }

public class ChildTest : Test
{
    public void DoSomething()
    {
        if (this._actionRequired != null)
            this._actionRequired();
    }
}
+1
source

All Articles