【问题标题】:Replace nested ForEach with Select if applicable如果适用,将嵌套的 ForEach 替换为 Select
【发布时间】:2009-08-25 22:17:27
【问题描述】:

是否可以将方法ForEach() 的用法替换为Select() 或其他方法,以便使用嵌套扩展方法在一个字符串中编写下一个代码?或者也许还有其他方法可以改进算法?

var list = new List<IStatementParser>();

System.IO.Directory.GetFiles(path, "*.dll")
    .ForEach(f => System.Reflection.Assembly.LoadFrom(f)
        .GetTypes()
        .Where(t => !t.IsInterface && typeof(IFoo).IsAssignableFrom(t))
        .ForEach(t => list.Add((IFoo)Activator.CreateInstance(t))));

return list.ToDictionary(k => k.Name, v => v.GetType());

它从实现IFoopath 中的程序集中加载所有类,并将它们添加到Dictionary&lt;string, Type&gt;,其中字符串为IFoo.Name

【问题讨论】:

    标签: c# .net linq extension-methods ienumerable


    【解决方案1】:
    var foos =
        from dllFile in Directory.GetFiles(path, "*.dll")
        from type in Assembly.LoadFrom(dllFile).GetTypes()
        where !type.IsInterface && typeof(IFoo).IsAssignableFrom(type)
        select (IFoo) Activator.CreateInstance(type);
    
    return foos.ToDictionary(foo => foo.Name, foo => foo.GetType());
    

    【讨论】:

    • 您需要一个 foo => foo.GetType() 参数作为 ToDictionary 调用中的值委托。否则,一个很好的答案。
    • 我只需要澄清上面'let'的用法,我就可以接受你的回答了。顺便说一句,我不需要 Dictionary,我需要 Dictionary where Type = IFoo (我编辑了初始帖子)——因为 FooFactory 将使用这个字典来创建 IFoo 的实例请求,在当前会话中可能根本不会发生。
    • 已编辑以包含 .GetType() 调用。 @Pavel 答案中的 let 子句是一种风格——你不需要拥有它,但他可能认为它更清晰。
    【解决方案2】:

    我认为这里根本不需要中间 List - 你可以这样做:

    return (from dll in Directory.GetFiles(path, "*.dll")
            let asm = Assembly.LoadFrom(dll)
            from t in asm.GetTypes()
            where !t.IsInterface && typeof(IFoo).IsAssignableFrom(t)
            select (IFoo)Activator.CreateInstance(t)
           ).ToDictionary(foo => foo.Name, foo => foo.GetType())
    

    顺便说一句,您可能还想在尝试实例化之前检查一个类型是否为abstract

    【讨论】:

    • 你能描述一下你用'let'做什么吗?下面的 Bryan Watts 没有
    • 这是一个方便/可读性的东西,不是绝对必要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2020-11-26
    • 2011-06-07
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多