简体   繁体   English

强制创建惰性对象

[英]Force Creating Lazy Objects

I'm being given a collection of Lazy items.我收到了一组Lazy物品。 I then want to forcibly 'create' them all in one go.然后我想一口气强行“创建”它们。

void Test(IEnumerable<Lazy<MailMessage>> items){
}

Normally with a Lazy item, the contained object won't be created until one of it's member's is accessed.通常对于Lazy项目,在访问其成员之一之前,不会创建包含的对象。

Seeing as there is no ForceCreate() method (or similar), I am forced to do the following:由于没有ForceCreate()方法(或类似方法),我被迫执行以下操作:

var createdItems = items.Where(a => a.Value != null && a.Value.ToString() != null).Select(a => a.Value);

Which is using ToString() to force created each item.这是使用ToString()强制创建每个项目。

Is there a neater way to forcibly create all items?有没有更简洁的方法来强制创建所有项目?

要获取所有延迟初始化值的列表:

var created = items.Select(c => c.Value).ToList();

You need two things to create all the lazy items, you need to enumerate all items (but not necessarily keep them), and you need to use the Value property to cause the item to be created.创建所有惰性项需要两件事,需要枚举所有项(但不一定保留它们),并且需要使用Value属性来创建项。

items.All(x => x.Value != null);

The All method needs to look at all values to determine the result, so that will cause all items to be enumerated (whatever the actual type of the collection might be), and using the Value property on each item will cause it to create its object. All方法需要查看所有值以确定结果,因此这将导致枚举所有项目(无论集合的实际类型是什么),并且在每个项目上使用Value属性将导致它创建其对象. (The != null part is just to make a value that the All method is comfortable with.) != null部分只是为了创建一个All方法可以接受的值。)

Seeing as there is no ForceCreate() method (or similar)看到没有 ForceCreate() 方法(或类似的)

You can always create a ForceCreate() extension method on Lazy<T> for this:您始终可以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;
    }
}

...accompanied by a ForEach extension method on IEnumerable<T> : ...伴随着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);
        }
    }
}

By combining these two extension methods you can then forcibly create them all in one go:通过结合这两种扩展方法,您可以一次强行创建它们:

items.ForEach(x => x.ForceCreate());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM