Estoy tratando de implementar un patrón de estrategia para permitirme aplicar algún "beneficio" a una "cuenta". En el siguiente código, no puedo agregar mi implementación de una interfaz a un diccionario que espera la interfaz. Creo que es algún tipo de problema contravarianza, pero se siente como si tuviera que ser capaz de hacer esto:Problema de herencia invariable
EDIT:
Dado que la respuesta parece ser que simplemente no es posible, alguna sugerencia sobre cómo lograr lo Voy por aquí?
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");
}
}
¿Está utilizando .NET 4? – Tejs
@Tejs sí Estoy usando .net 4.0 – scottm