我有一些类似以下的策略:
public abstract class AbstractDoSomeStuffStrategy
{
public abstract string DoMySpecificFoo(string necessaryParameter);
public abstract string DoMySpecificBar(string necessaryParameter);
}
public class AmazingConcreteStrategy : AbstractDoSomeStuffStrategy
{
public override string DoMySpecificFoo(string necessaryParameter)
{
return "Amazing concrete foo! Have a " + necessaryParameter;
}
public override string DoMySpecificBar(string necessaryParameter)
{
return "Amazing concrete bar! Have a " + necessaryParameter;
}
}
public class SubparConcreteStrategy : AbstractDoSomeStuffStrategy
{
public override string DoMySpecificBar(string necessaryParameter)
{
throw new NotImplementedException();
}
public override string DoMySpecificFoo(string necessaryParameter)
{
return "Meh. Whatever. This foo is garbage so take your " + necessaryParameter + " back.";
}
}
还有一个如下的包装器:
public class StrategyWrapper<T> where T : AbstractDoSomeStuffStrategy
{
public T MyStrategy { get; set; }
public StrategyWrapper()
{
MyStrategy = Activator.CreateInstance<T>();
}
}
并且正在尝试使用包装器,如下所示:
public class SomeController
{
private Dictionary<string, StrategyWrapper<AbstractDoSomeStuffStrategy>> _strategyMap { get; set; }
public SomeController()
{
_strategyMap = new Dictionary<string, StrategyWrapper<AbstractDoSomeStuffStrategy>>();
_strategyMap.Add("AmazingConcrete", new StrategyWrapper<AmazingConcreteStrategy>());
_strategyMap.Add("SubparConcrete", new StrategyWrapper<SubparConcreteStrategy>());
}
public AbstractDoSomeStuffStrategy GetStrategy(string name)
{
return _strategyMap[name].MyStrategy;
}
}
尝试执行以下操作:
namespace ShamelessSOQuestions
{
class Program
{
static void Main(string[] args)
{
AbstractDoSomeStuffStrategy myStrategy;
var controller = new SomeController();
myStrategy = controller.GetStrategy("AmazingConcrete");
Console.WriteLine(myStrategy.DoMySpecificFoo("woohoo"));
}
}
}
但是,在我的控制器上,它不喜欢我的_strategyMap.Add(...StrategyWrapper<AnythingOtherThanDoSomeStuffStrategy>)
很显然,我正在以所有错误的方式进行操作。有人可以帮我了解如何使这项工作适用于我可以四处使用类型安全性但仍使其相当灵活的地方吗?