How to override parameter defined in interface met

2019-04-11 15:52发布

问题:

I have these:

public class TennisPlayer
{

}

public class RogerFederer : TennisPlayer
{

}

public class RafaelNadal : TennisPlayer
{

}

And then I have some classes with methods, like these:

public abstract class Manager
{
    protected abstract void ScheduleFriendlies(TennisPlayer player);
}

public class RafaelNadalManager : Manager
{
    public void ScheduleFriendlies(RafaelNadal rn)
    {
        //throw new NotClayException();
    }
}

public class RogerFedererManager : Manager
{
    public void ScheduleFriendlies(RogerFederer rf)
    {
        //throw new NotGrassException();
    }
}

//'RafaelNadalManager' does not implement inherited abstract member 'Manager.ScheduleFriendlies(TennisPlayer)'

The thing I'm trying to achieve is that I would want to have child classes of Manager but every such class will be tied to one player and hence the methods in those child classes (Manager classes) will be specific to that player. In other words Roger should have his own ScheduleFriendlies while Rafael should have his own.

How do I go about this? Alternate designs would do, but keep in mind:

What I can alter: The inheritances, its routes etc

But do not have the luxury to: Take off child manager classes and merge into one (in other words, I need RogerFederer and RogerFedererManager as separate classes).

I tried this:

public abstract class Manager
{
    protected abstract bool ScheduleFriendlies<T>(T player) where T : TennisPlayer;
}

public class RafaelNadalManager : Manager
{
    protected override bool ScheduleFriendlies<T>(T player)
    {
        //but how do I enforce the caller that only RafaelNadal object can be 
        //passed to this but not RogerFederer?
    }
}

回答1:

You were close, but you need the class generic, not just the method:

public abstract class Manager<T> where T : TennisPlayer
{
    protected abstract bool ScheduleFriendlies(T player);
}

You could then use:

public class RafaelNadalManager : Manager<RafaelNadal>
{
     protected override bool ScheduleFriendlies(RafaelNadal player)
     {}
}