SepGuest
SepGuest

Reputation: 127

C# Delegates in Abstract and Subclass

I am programming a Programme for Vacations Control for Companies (only to learn, not serious). Now I have a Abstract Class called Employee. and 4 stages of Employees.

EveryOne has it own class:

The Normal Worker can ask for Vacations, the SAL can say ok or deny the Request. If he says ok it will go to the CHRO. He can veto it or pass it. The CEO is the last Instance who can veto it.

All classes inherits the Abstract Class. The Abstract Class has a delegate called

public delegate void applyVacations(Vacation what_vacations, bool pass_or_deny)

All Subclasses have a Method

void apply(Vacation what_vacation, bool pass_or_deny)

except of the NormalWorker. And the Constructors of the subclasses shall push this apply Method to the delegate.

passing the vacation request is final for all Instances.

Example:

namespace ex
{
    public abstract class A
    {
        public delegate void foo();
        public A()
        { }
    }

    class B : A
    {
        public B()
        {
            A.foo = childfoo;  // Does not work
        }
        public void childfoo()
        {/* Do something*/}
    }

}

Greetings

Upvotes: 0

Views: 156

Answers (2)

AMS
AMS

Reputation: 439

foo is a delegate so it's a type

in B constructor you should write

foo handler = childfoo;

then you can call handler()

namespace ex
{
    public abstract class A
    {
        public delegate void foo();
        public A()
        { }
    }

    class B : A
    {
        private foo handler;

        public B()
        {
            handler = childfoo;
        }

        public void callHandlerHere()
        {
            handler();
        }

        public void childfoo()
        {/* Do something*/}
    }
}

this is for exemple purpose of course

B b = new B();
b.callHandlerHere() // all object inheriting A can habe a callHandlerHere function for exemple

Upvotes: 0

aevitas
aevitas

Reputation: 3833

You need to create a variable of type foo and then assign childfoo to it, like so:

    private foo _handler;
    public B()
    {
        // Assign our handler for the foo delegate.
        _handler = childfoo;

        // Now we can call it.
        _handler();
    }

Upvotes: 2

Related Questions