[英]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.