我已实现(使用System.Configuration
命名空间)并配置了下一个App.config
结构:
<bot>
<strategies>
<add name="TestStrategy" type="Bot.Strategy.Test" >
<indicators>
<add name="Foo" type="Bot.Indicators.Foo, Bot" />
<add name="Bar" type="Bot.Indicators.Bar, Bot" />
</indicators>
<orders>
<add id="123" amount="0.1" />
</orders>
</add>
</strategies>
</bot>
下一课:
class TestStrategy : IStrategy
{
public TestStrategy(IEnumerable<IIndicator> indicators, IEnumerable<Order> orders) { }
}
interface IIndicator { }
class Order
{
public int ID { get; set; }
public double Amount { get; set; }
}
那么我怎样才能读取我的App.config以使用LINQ实例化IEnumerable<IStrategy>
使用适当的IEnumerable<IIndicator>
和IEnumerable<Order>
调用每个构造函数?
我已经接下来了:
var section = ((BotSection)ConfigurationManager.GetSection("bot"));
return from strategy in section.Strategies
let strategyType = Type.GetType(strategy.Type)
where !strategyType.IsInterface && !strategyType.IsAbstract && typeof(IStrategy).IsAssignableFrom(strategyType)
select (IStrategy)Activator.CreateInstance(strategyType, ?);
答案 0 :(得分:1)
如果您的BotSection
定义正确,您可以执行此操作(请注意子查询):
return
from strategy in section.Strategies
let strategyType = Type.GetType(strategy.Type)
where !strategyType.IsInterface && !strategyType.IsAbstract
&& typeof(IStrategy).IsAssignableFrom(strategyType)
let indicators = (
from indicator in strategy.Indicators
let indicatorType = Type.GetType(indicator.Type)
select (IIndicator)Activator.CreateInstance(indicatorType))
let orders = (
from order in strategy.Orders
let id = order.Id
select new Order { Id = order.Id, Amount = order.Amount })
select (IStrategy)Activator.CreateInstance(strategyType, indicators, orders);