0

最近我采用了一种方便的方法来确保树状结构成员知道他们的父节点:

private metaCollection<metaPage> _servicePages;
/// <summary>
/// Registry of service pages used by this document
/// </summary>
[Category("metaDocument")]
[DisplayName("servicePages")]
[Description("Registry of service pages used by this document")]
public metaCollection<metaPage> servicePages
{
    get
        {
        if (_servicePages == null) {
            _servicePages = new metaCollection<metaPage>();
            _servicePages.parent = this;
        }
        return _servicePages;
    }
}

(概念是在属性获取方法中为私有字段创建实例)

我很想知道这种模式是否有一些众所周知的名字?甚至更多:这种做法是否存在已知问题/不良影响?

谢谢!

4

1 回答 1

1

是的,它被称为延迟初始化。从Wikipedia Lazy Loading 页面上的示例:

延迟初始化

主条目:延迟初始化

使用延迟初始化,要延迟加载的对象最初设置为 null,并且对对象的每个请求都会检查 null 并在首先返回它之前“即时”创建它,如以下 C# 示例所示:

private int myWidgetID;
private Widget myWidget = null;

public Widget MyWidget 
{
    get 
    {
        if (myWidget == null) 
        {
            myWidget = Widget.Load(myWidgetID);
        }    

        return myWidget;
    }
}
于 2017-05-09T00:27:03.837 回答