Home > database >  C# overriding with child class
C# overriding with child class

Time:11-12

everyone!

Lately I've stuck with some project. What I want to do? Make child method overloading with overriding method signature (not really, cause child method argument is child class of base methos argument). I've have some number of classes. Let's say it's like this:

public class ActionEventArgs : EventArgs
{
    public Creature actor;
}

public class LocationEventArgs : ActionEventArgs
{
    public Location loc;
}

public class Action
{
    public virtual void Do(object sender, ActionEventArgs e)
    {
        //... do something with it;
    }
}

public class LocationAction : Action
{
    public override void Do(object sender, LocationEventArgs e) // error, signatures differs
    {
        //... do something with it;
    }
}

public class MainClass
{
    public Action a { get; protected set; }

    public void InitAction()
    {
        a = new LocationAction();
    }

    public void DoAction(Creature actor, Location location)
    {
        a.Do(this, new LocationEventArgs() { actor = actor, loc = location });
    }
}

Well, it didn't work because of different methods signatures. Ok. Of course, I can use something like class checks like:

public class LocationAction : Action
{
    public override void Do(Action sender, ActionEventArgs e)
    {
        if (!(e is LocationEventArgs)) throw new ArgumentException("e must be LocationEventArgs");
        //... do something with it;
    }
}

But I don't really like it, cause it's only runtime thing. So, question is: how to do this properly. Is there a way?

CodePudding user response:

I think you want to use generics:

public class Action<TArg> where TArg : ActionEventArgs
{
    public virtual void Do(object sender, TArg e)
    {
        // can access 'e.actor'
    }
}

public class LocationAction : Action<LocationEventArgs>
{
    public override void Do(object sender, LocationEventArgs e)
    {
        // can access 'e.actor' and 'e.loc'
    }
}

CodePudding user response:

I think what you are willing to do goes against the principle itself. You can't override and change the parameters. maybe add a

public override void Do(object sender, LocationEventArgs e) // error, signatures differs { //... do something with it; }

in your action class ?

CodePudding user response:

Hoc can I forgot about generics... Thanks, will try out.

  • Related