LazyInitializer 類別

定義

提供延遲初始化常式。Provides lazy initialization routines.

public ref class LazyInitializer abstract sealed
public static class LazyInitializer
type LazyInitializer = class
Public Class LazyInitializer
繼承
LazyInitializer

範例

下列範例示範如何使用 EnsureInitialized,以使用布林值來延遲初始化值,以追蹤初始化是否已經發生,以及要當做相互排除鎖定使用的物件。The following example demonstrates how to use EnsureInitialized to lazily initialize a value using a Boolean value to track whether initialization has already happened and an object to use as the mutual exclusion lock.

Dim _data As ExpensiveData = Nothing  
Dim _dataInitialized As Boolean = False  
Dim _dataLock As Object = Nothing  
'    ...  
Dim name = LazyInitializer.EnsureInitialized(_data, _dataInitialized, _dataLock)  
ExpensiveData _data = null;  
bool _dataInitialized = false;  
object _dataLock = new object();  

//  ...  
  
ExpensiveData dataToUse = LazyInitializer.EnsureInitialized(ref _data, ref _dataInitialized, ref _dataLock);  

備註

這些常式會避免需要配置專用的延遲初始化實例,而是改為使用參考,以確保目標在存取時已初始化。These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using references to ensure targets have been initialized as they are accessed.

方法

EnsureInitialized<T>(T)

如果目標參考型別尚未初始化,則使用該型別的無參數建構函式來進行初始化。Initializes a target reference type with the type's parameterless constructor if it hasn't already been initialized.

EnsureInitialized<T>(T, Boolean, Object)

如果目標參考型別或實值型別尚未初始化,則使用其無參數的建構函式來進行初始化。Initializes a target reference or value type with its parameterless constructor if it hasn't already been initialized.

EnsureInitialized<T>(T, Boolean, Object, Func<T>)

如果目標型別尚未初始化,則使用指定的函式來初始化目標的參考或實值型別。Initializes a target reference or value type by using a specified function if it hasn't already been initialized.

EnsureInitialized<T>(T, Func<T>)

如果目標型別尚未初始化,則使用指定的函式來初始化目標的參考型別。Initializes a target reference type by using a specified function if it hasn't already been initialized.

EnsureInitialized<T>(T, Object, Func<T>)

若尚未初始化,則使用指定的函式初始化目標參考型別。Initializes a target reference type with a specified function if it has not already been initialized.

適用於

執行緒安全性

LazyInitializer 的方法都是安全線程,而且可以從多個執行緒同時呼叫。The methods of LazyInitializer are thread-safe and may be called from multiple threads concurrently.

另請參閱