缓存属性Getter中的密集计算

Art*_*ium 6 c#

在以下代码中:

public class SomeClass
{
    // ... constructor and other stuff

    public in SomeProperty
    {
        get
        {
            return SomeHeayCalculation();
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

我认为该类是不可变的,因此每次SomeProperty访问时,都应返回相同的值.我的问题是,是否有可能避免每次计算值.是否有一些内置的机制来缓存这些东西?

Jon*_*eet 16

是的 - Lazy<T>假设您使用的是.NET 4:

public class SomeClass
{
    private readonly Lazy<Foo> foo = new Lazy<Foo>(SomeHeayCalculation);
    // ... constructor and other stuff

    public Foo SomeProperty
    {
        get
        {
            return foo.Value;
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

我假设你试图避免在永远不会访问该属性的情况下执行计算.否则,只需在施工时预先执行.

请注意,属性通常被理解为"便宜"以进行评估 - 并且当您将此变为懒惰以便以后的访问是便宜的时,在第一次访问以使属性不合适时,这仍然可能"足够".考虑一种ComputeXyz方法.


Chr*_*den 5

只需缓存计算,private variable如下所示:

public class SomeClass
{        
    // ... constructor and other stuff

    private int? calculation = null;

    public int SomeProperty
    {
        get
        {
            if (!calculation.HasValue)
                calculation = SomeHeayCalculation();

            return calculation.Value;
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)