简体   繁体   中英

Force Creating Lazy Objects

I'm being given a collection of Lazy items. 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.

Seeing as there is no ForceCreate() method (or similar), I am forced to do the following:

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.

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.

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. (The != null part is just to make a value that the All method is comfortable with.)

Seeing as there is no ForceCreate() method (or similar)

You can always create a ForceCreate() extension method on Lazy<T> for this:

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> :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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