我有下一个 LINQ 查询来读取 App.config 以使用内部所述的完全限定类型实例化对象:
var strategies = from strategy in section.Strategies
let indicators = (
from indicator in strategy.Indicators
select (IIndicatorReader)Activator.CreateInstance(Type.GetType(indicator.Type), bot.Mt, section.Symbol))
let orders = (
from order in strategy.Orders
select new OrderInfo(order.Id, order.Operation.Value, order.Amount))
select (IStrategy)Activator.CreateInstance(Type.GetType(strategy.Type), section.Symbol, strategy.Amount, strategy.Limit, indicators, orders);
所以每次在我调用的策略里面
indicatorList.Select(i => i.Operation)
发生此实例化:
(IIndicatorReader)Activator.CreateInstance(Type.GetType(indicator.Type), bot.Mt, section.Symbol))
并调用适当的类的构造函数。
但是在 App.config 中首先说明的指标被实例化了两次,其他的都是一次。怎么会这样??我很乐意提供所需的任何其他信息。
我的指标集合:
public class IndicatorElementCollection : ConfigurationElementCollection, IEnumerable<IndicatorElement>
{
...
public new IEnumerator<IndicatorElement> GetEnumerator()
{
return this.OfType<IndicatorElement>().GetEnumerator();
}
}
从非泛型到泛型的转换的实现GetEnumerator()
取自关于 SO 的这个问题。
另一个实现:
foreach (OrderElement element in (System.Collections.IEnumerable)this)
{
yield return element;
}
以同样的方式工作。