2010-12-14 2 views
0

Я выполнил (с использованием System.Configuration имен) и сконфигурированный следующий App.config структуру:Чтение app.config с помощью LINQ

<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 для создания экземпляра IEnumerable<IStrategy>, вызывающего конструктор каждого с соответствующими IEnumerable<IIndicator> и IEnumerable<Order> с использованием LINQ?

У меня есть уже в следующем:

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, ?); 
+1

Лично я бы не пропустить типы, которые Арен 't конкретный (как и в предложении 'where'), но я бы бросил конкретное исключение, описывающее фактическую проблему, или пусть« Activator »выбросит это исключение для вас. – Steven

ответ

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); 
+0

Невозможно избежать использования вложенных запросов, верно? – abatishchev

+0

Вы можете реорганизовать создание «strategyType» и вспомогательных запросов к методу и выбрать «CreateStrategy (strategy)», но это действительно не удаляет вложенные запросы. Я не знаю другого пути. – Steven

Смежные вопросы