मैं एक रणनीति पैटर्न को लागू करने की कोशिश कर रहा हूं ताकि मुझे "खाता" में कुछ "लाभ" लागू करने की अनुमति दी जा सके। नीचे दिए गए कोड में, मैं इंटरफ़ेस की अपेक्षा रखने वाले एक शब्दकोश में इंटरफ़ेस का अपना कार्यान्वयन नहीं जोड़ सकता। मुझे लगता है कि यह contravariance समस्या किसी तरह का है, लेकिन यह है कि मैं ऐसा करने में सक्षम होना चाहिए लगता है:Invariant विरासत समस्या
संपादित करें:
के बाद से जवाब यह है कि यह सिर्फ संभव नहीं है, हो रहा है कि कैसे प्राप्त करने के लिए पर कोई सुझाव क्या मैं यहाँ जा रहा हूँ?
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");
}
}
क्या आप .NET 4 का उपयोग कर रहे हैं? अमान्य विचरण: – Tejs
@Tejs हाँ मैं .net 4.0 – scottm