Проблема инвариантного наследования

Я пытаюсь реализовать шаблон стратегии, чтобы позволить мне применить некоторую «выгоду» к «учетной записи» ". В приведенном ниже коде я не могу добавить свою реализацию интерфейса в словарь, ожидающий интерфейса. Я думаю, что это какая-то проблема контравариантности, но мне кажется, что я смогу это сделать:

EDIT:
Поскольку ответ, кажется, просто невозможен, какие-либо предложения о том, как достичь того, что я собираюсь здесь сделать?

void Main()
{
    var provider = new BenefitStrategyProvider();

    var freeBenefit = new FreeBenefit();

    var strategy = provider.GetStrategy(freeBenefit);

    strategy.ApplyBenefit(freeBenefit, new Account());

}

public class BenefitStrategyProvider
{
    private Dictionary<Type, IBenefitStrategy<BenefitBase>> _strategies = new Dictionary<Type, IBenefitStrategy<BenefitBase>>();

    public BenefitStrategyProvider()
    {
        /* Why can't I add this? */
        _strategies.Add(typeof(FreeBenefit), new FreeBenefitStrategy());
    }

    public IBenefitStrategy<BenefitBase> GetStrategy(BenefitBase benefit)
    {
        return _strategies[benefit.GetType()];
    }

}

public class Account {}

public abstract class BenefitBase
{
    public string BenefitName {get;set;}    
}

public class FreeBenefit : BenefitBase {}

public interface IBenefitStrategy<T> where T: BenefitBase
{
    void ApplyBenefit(T benefit, Account account);
}

public class FreeBenefitStrategy : IBenefitStrategy<FreeBenefit>
{
    public void ApplyBenefit(FreeBenefit benefit, Account account)
    {
        Console.WriteLine("Free Benefit applied");
    }
}
7
задан scottm 7 May 2011 в 02:59
поделиться