如何建立一个 IEnumerable



在构建配置文件IEnumerable时遇到问题。 Mapper.Initialize只需要对项目中的所有配置文件运行一次。 尝试设置profiles = new List<Profile>(),但配置文件计数始终为 0。

IEnumerable<Profile> profiles = null;
var profileType = typeof(Profile);
var assemblies = AppDomain.CurrentDomain.GetAssemblies()
    .Where(a => a.FullName.Contains("Cars.Data"));
foreach (var assembly in assemblies)
{
    profiles.Concat(
       assembly.GetTypes()
           .Where(t => profileType.IsAssignableFrom(t) &&
                  t.GetConstructor(Type.EmptyTypes) != null)
           .Select(Activator.CreateInstance)
           .Cast<Profile>());
}
Mapper.Initialize(c => profiles.ForEach(c.AddProfile));
IEnumerable<T>是不

可变的。

.Concat()返回一个带有串联序列的新IEnumerable<T>;您将忽略此结果。

profiles.Concat()在与 null 一起使用时给出ArgumentNullException。 由于您将列表设置为 null,因此会收到此错误。 您的解决方案是使用 List 和 AddRange 方法作为 follws

List<Profile> profiles = new List<Profile>();
profiles.AddRange(assembly.GetTypes()
           .Where(t => profileType.IsAssignableFrom(t) &&
                  t.GetConstructor(Type.EmptyTypes) != null)
           .Select(Activator.CreateInstance)
           .Cast<Profile>());
作为对

@SLaks完全正确答案的补充,我将在这里介绍一个正确的 LINQ 解决方案。但问题本身是 OP 没有分配他新构建的懒惰表达式(好吧,monad)。

var profileType = typeof(Profile);
var profiles = AppDomain.CurrentDomain.GetAssemblies()
    .Where(a => a.FullName.Contains("Cars.Data"))
    .SelectMany(a => 
           a.GetTypes()
           .Where(t => profileType.IsAssignableFrom(t) &&
                  t.GetConstructor(Type.EmptyTypes) != null)
           .Select(Activator.CreateInstance) // Have you overloaded this?
           .Cast<Profile>())
     .ToList(); // ToList enumerates

甚至更容易阅读:

var profileType = typeof(Profile);
var profiles = 
     from a in AppDomain.CurrentDomain.GetAssemblies()
     where a.FullName.Contains("Cars.Data")
     from t in a.GetTypes()
     where profileType.IsAssignableFrom(t)
       and t.GetConstructor(Type.EmptyTypes) != null
     select (Profile)Activator.CreateInstance; // Have you overloaded this?
var profileList = profiles.ToList(); // Enumerate if needed.

LINQ(和IEnumerable<T>)的整个思想是不使用显式类和构造函数。

相关内容

最新更新