是否可以将方法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());


它从实现pathIFoo中的程序集中加载所有类,并将它们添加到字符串为Dictionary<string, Type>IFoo.Name中。

最佳答案

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());

关于c# - 如果适用,将嵌套的ForEach替换为Select,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1331343/

10-12 15:55