[英]Force Creating Lazy Objects
我收到了一组Lazy
物品。 然后我想一口气强行“创建”它们。
void Test(IEnumerable<Lazy<MailMessage>> items){
}
通常对于Lazy
项目,在访问其成员之一之前,不会创建包含的对象。
由于没有ForceCreate()
方法(或类似方法),我被迫执行以下操作:
var createdItems = items.Where(a => a.Value != null && a.Value.ToString() != null).Select(a => a.Value);
这是使用ToString()
强制创建每个项目。
有没有更简洁的方法来强制创建所有项目?
要获取所有延迟初始化值的列表:
var created = items.Select(c => c.Value).ToList();
创建所有惰性项需要两件事,需要枚举所有项(但不一定保留它们),并且需要使用Value
属性来创建项。
items.All(x => x.Value != null);
All
方法需要查看所有值以确定结果,因此这将导致枚举所有项目(无论集合的实际类型是什么),并且在每个项目上使用Value
属性将导致它创建其对象. ( != null
部分只是为了创建一个All
方法可以接受的值。)
看到没有 ForceCreate() 方法(或类似的)
您始终可以ForceCreate()
在Lazy<T>
上创建ForceCreate()
扩展方法:
public static class LazyExtensions
{
public static Lazy<T> ForceCreate<T>(this Lazy<T> lazy)
{
if (lazy == null) throw new ArgumentNullException(nameof(lazy));
_ = lazy.Value;
return lazy;
}
}
...伴随着IEnumerable<T>
上的ForEach
扩展方法:
public static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
if (enumerable == null) throw new ArgumentNullException(nameof(enumerable));
if (action == null) throw new ArgumentNullException(nameof(action));
foreach (var item in enumerable)
{
action(item);
}
}
}
通过结合这两种扩展方法,您可以一次强行创建它们:
items.ForEach(x => x.ForceCreate());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.