3

以下片段展示了我最近经常遇到的一个问题。

基本上我想知道是否有比使用继承更好的解决方案来隐藏属性的支持值,如图所示。

作为一个附带问题,我的非编译解决方案所暗示的功能是否可能对未来版本的 C# 有好处?

// This is a service that supplies a value but doesn't want to be called 
// until needed.
static class Service
{
    public static int GetP()
    {
        Console.WriteLine ("doing work...");
        return 1;
    }
}

// This is a class that implements a property which calls the service
// the first time that property is accessed but nothing stops the
// same code from accidentally referencing the uninitialized backing value.
class C
{
    void F()
    {
        // Easy to accidentally reference backing value of property
        Console.WriteLine (this.p);
    }

    int p = 0;
    int P
    {
        get
        {
            if(p == 0)
                p = Service.GetP();
            return p;
        }
    }
}

使用具有私有支持值的继承和受保护属性的解决方案。

// This class hides the backing value and exposed the property the derived class.
class CBase
{
    int p = 0;
    protected int P
    {
        get
        {
            if(p == 0)
                p = Service.GetP();
            return p;
        }
    }
}

class C1 : CBase
{
    void F()
    {
        // Now I can't see the backing value but I've used inheritance for the sole purpose of hiding it
        Console.WriteLine (this.P);
    }
}

如果 const 可能位于实例级方法/属性的主体中,该方法/属性会延迟设置直到第一次运行时使用,那该怎么办?

class D
{
    int P
    {
        get
        {
            const int a = Service.GetP(); // Doesn't compile
            return a;
        }
    }
}
4

1 回答 1

3

如果您使用的是 .net 4,只需使用Lazy

class C
{
    private Lazy<int> p = new Lazy<int>(() => Service.GetP());

    private int P
    {
        get
        {
            return p.Value;
        }
    }
}

第一次访问 Lazy.Value 时,将调用提供给构造函数的函数来初始化值。

于 2012-09-07T22:14:02.043 回答