如何用更丰富的类型覆盖接口方法中定义的参数? [英] How to override parameter defined in interface method with richer type?

查看:20
本文介绍了如何用更丰富的类型覆盖接口方法中定义的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些:

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

我想要实现的目标是我希望拥有 Manager 的子类,但是每个这样的类都将绑定到一个玩家,因此这些子类中的方法(Manager 类)将特定于该玩家.换句话说,Roger 应该有他自己的 ScheduleFriendliesRafael 应该有他自己的.

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.

我该怎么做?其他设计也可以,但请记住:

我可以改变什么:继承、路线等

但没有奢侈:去掉子管理器类并合并为一个(换句话说,我需要RogerFedererRogerFedererManager 作为单独的类).

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

我试过了:

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

推荐答案

你已经很接近了,但你需要类泛型,而不仅仅是方法:

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);
}

然后您可以使用:

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

这篇关于如何用更丰富的类型覆盖接口方法中定义的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆