Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ读取app.config_C#_Linq_App Config_Linq To Objects - Fatal编程技术网

C# 使用LINQ读取app.config

C# 使用LINQ读取app.config,c#,linq,app-config,linq-to-objects,C#,Linq,App Config,Linq To Objects,我已经实现(使用System.Configurationnamespace)并配置了nextApp.config结构: <bot> <strategies> <add name="TestStrategy" type="Bot.Strategy.Test" > <indicators> <add name="Foo" type="Bot.Indicators.Fo

我已经实现(使用
System.Configuration
namespace)并配置了next
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>

如果正确定义了
BotSection
,则可以执行此操作(注意子查询):


就我个人而言,我不会跳过不具体的类型(就像您在
where
子句中所做的那样),但我会抛出一个描述实际问题的特定异常,或者让
Activator
为您抛出该异常。您可以将
strategyType
和子查询的创建重构为一个方法,然后执行
选择CreateStrategy(strategy)
,但这并不能真正删除嵌套查询。我不知道还有别的办法。
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; }
}
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, ?);
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);