使用lambdas进行惰性字段初始化 [英] Lazy field initialization with lambdas

查看:98
本文介绍了使用lambdas进行惰性字段初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在没有if语句的情况下实现惰性字段初始化(或延迟初始化)并利用lambdas。所以,我想对以下 Foo 属性采取相同的行为,但如果没有,则

I would like to implement lazy field initialization (or deferred initialization) without an if statement and taking advantage of lambdas. So, I would like to have the same behavior of the following Foo property but without the if:

class A<T>{
    private T fooField;

    public T getFoo(){
        if( fooField == null ) fooField = expensiveInit();
        return fooField;
    }
}

忽略此解决方案无法保证安全使用的事实用于:1)多线程; 2) null 作为 T的有效值

Ignore the fact that this solution is not guaranteeing safe use for: 1) multi-threading; 2) null as a valid value of T.

因此,为了表达 fooField 的初始化被推迟到第一次使用的意图,我想声明 fooField 类型供应商< T> ,例如:

So, to express the intention that the initialization of the fooField is deferred until its first use I would like to declare the fooField of the type Supplier<T> such as:

class A<T>{
   private Supplier<T> fooField = () -> expensiveInit();

   public T getFoo(){
      return fooField.get();
   }
}

然后在 getFoo 属性我只返回 fooField.get()。但是现在我希望下次调用 getFoo 属性,避免 expensiveInit()并返回之前的 T 实例。

and then in the getFoo property I would just return fooField.get(). But now I want that next invocations to getFoo property avoid the expensiveInit() and just return the previous T instance.

如果不使用,如果,我该如何实现?

How can I achieve that without using an if?

尽管命名约定并用 => - > c $ c>,那么这个例子也可以在C#中考虑。但是,.NET Framework版本4已经提供了具有所需语义的 Lazy< T>

Despite naming conventions and replacing the ->by =>, then this example could be also considered in C#. However, NET Framework version 4 already provides a Lazy<T> with the desired semantics.

推荐答案

在您的实际lambda中,您只需使用新的lambda更新 fooField ,例如:

Within your actual lambda, you can simply update the fooField with a new lambda, such as:

class A<T>{
    private Supplier<T> fooField = () -> {
       T val = expensiveInit();
       fooField = () -> val;
       return val;
    };

    public T getFoo(){
       return fooField.get();
    }
}

同样,此解决方案不是线程安全的,因为.Net Lazy< T> ,并且不确保对 getFoo 属性的并发调用返回相同的结果。

Again this solution is not thread-safe as is the .Net Lazy<T>, and does not ensure that concurrent calls to the getFoo property return the same result.

这篇关于使用lambdas进行惰性字段初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆