C# 中的 LazyAction?

LazyAction in C#?

C# 标准 API 是否有延迟初始化代码块的方法?

我知道 Lazy<T> 但它是为了初始化一个变量,并且需要一个 returns 一个 T 的函数。我想要更像 LazyAction 的东西。

private _lazyInit = new LazyAction( () => {
    ...
    // Do something big like get some data from DB
    ...
    _myField1 = ...
    _myField2 = ...
    ...
    do no return stuff.
}

public object get_Field1() { _lazyInit.EnsureDone(); return _myfield1; }
public object get_Field2() { _lazyInit.EnsureDone(); return _myfield2; }

为了线程安全,LazyAction 将有一些机制来确保它只有 运行 一次。

虽然我更喜欢 Jeroen Mostert 的提议,但您可以这样做:

创建一个 class 来保存您的初始化方法:

class LazyInitializer
{
    private readonly Action initFunc;

    class State { public bool Initialized = false; }

    public LazyInitializer(Action initFunc)
    {
        this.initFunc = initFunc;
    }

    public Action CreateInitializer()
    {
        var state = new State();

        return () =>
        {
            lock (state)
            {
                if (state.Initialized == false)
                {
                    initFunc();
                    state.Initialized = true;
                }
            }
        };
    }
}

然后像这样使用它:

var lazyInit = new LazyInitializer(() =>
{
    //here your initialization code
    ...
    _myField1 = ...
    _myField2 = ...
    ...
});

//Create the initializer action
var initialize = lazyInit.CreateInitializer();

//use it like:
public object get_Field1() { initialize(); return _myfield1; }
public object get_Field2() { initialize(); return _myfield2; }