如何覆盖接口方法定义更丰富的类型参数?(How to override parameter defi

2019-08-01 04:33发布

我有这些:

public class TennisPlayer
{

}

public class RogerFederer : TennisPlayer
{

}

public class RafaelNadal : TennisPlayer
{

}

然后,我有一些类与方法,像这样的:

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)'

我想实现的事情是,我会希望有子类Manager ,但每一个这样的类将被捆绑到一个球员,因此在这些子类(方法Manager类)将特定于该玩家。 换句话说Roger应该有自己的ScheduleFriendliesRafael应该有他自己的。

我怎么去呢? 备选设计会做,但要记住:

我可以改变 :在继承,它的路线等

但不奢侈到 :脱掉孩子管理类和合并成一个(换句话说,我需要RogerFedererRogerFedererManager作为单独的类)。

我尝试这样做

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?
    }
}

Answer 1:

你是接近,但你需要的类通用的,不只是方法:

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

然后,您可以使用:

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


文章来源: How to override parameter defined in interface method with richer type?