2010-12-21 92 views
4

我旁边LINQ查询读取的App.config实例使用完全合格的对象类型里面说:LINQ和Activator.CreateInstance()创建副本

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中首先声明的指示器实例化为两次,所有其他 - 一次。怎么会这样??我会很乐意提供任何所需的附加信息。


我的指示器集合:从非通用

实施 GetEnumerator()
public class IndicatorElementCollection : ConfigurationElementCollection, IEnumerable<IndicatorElement> 
{ 
    ... 

    public new IEnumerator<IndicatorElement> GetEnumerator() 
    { 
     return this.OfType<IndicatorElement>().GetEnumerator(); 
    } 
} 

转换到通用从this question on SO拍摄。

另一种实现:

foreach (OrderElement element in (System.Collections.IEnumerable)this) 
{ 
    yield return element; 
} 

作品以同样的方式。

回答

1

每当您拨打GetEnumerator时,都会重新评估LINQ表达式indicators。您需要通过调用ToListToArray来强制进行一次评估。如果您期待很多指标,这当然会导致内存空间问题。

+0

我重写`IIndicatorReader`并使用`ToArray()`为这两个子查询,但仍然得到重复的实例。在调试器中思考我在策略实例化之前看到一个2个指标的数组。可能是由于我实现了非泛型的`GetEnumerator()`转换? (我更新了我的帖子) – abatishchev 2010-12-21 20:57:07