如何使此属性仅在首次访问时创建
本文关键字:访问 创建 何使此 属性 | 更新日期: 2023-09-27 18:20:05
我有以下代码:
/// <summary>
/// BrowserFactory responsible for deciding if you should receive a shared or isolated browser instance.
/// </summary>
public static class BrowserFactory
{
/// <summary>
/// Shared Browser Instance
/// </summary>
private static SharedBrowser _sharedBrowser;
/// <summary>
/// The window handle of the shared browser instance.
/// </summary>
private static string _sharedHwnd;
/// <summary>
/// The last thread id to access the shared browser.
/// </summary>
private static int _sharedThreadId;
static BrowserFactory()
{
Shared= new SharedBrowser();
}
private static SharedBrowser Shared
{
get
{
var currentThreadId = GetCurrentThreadId();
if (currentThreadId != _sharedThreadId)
{
_sharedBrowser = IE.AttachTo<SharedBrowser>(Find.By("hwnd", _sharedHwnd));
_sharedThreadId = currentThreadId;
}
return _sharedBrowser;
}
set
{
_sharedBrowser = value;
_sharedHwnd = _sharedBrowser.hWnd.ToString();
_sharedThreadId = GetCurrentThreadId();
}
}
public static Browser GetBrowser()
{
return BrowserSettings.UseSharedBrowser ? Shared : new Browser();
}
}
如何使其仅在首次访问SharedBrowser对象时而不是在构造函数中实例化该属性?
起初,我想在Shared属性中执行此操作,但从属性get调用集合似乎很奇怪。
我还想过将_sharedBrowser封装在.NET 4.0 Lazy对象中,但我不知道如何直接实例化封装在Lazy中的东西,这是当用户获得(重新附加后)时我需要在Shared属性中执行的操作。
我不知道如果不复制我的共享属性,我怎么能做到这一点。在.get.中设置逻辑
有什么想法吗?
您可以将此模式用于静态成员和实例成员:
private SomeType _myProperty;
public SomeType MyProperty
{
get
{
if (_myProperty == null) {
_myProperty = new SomeType();
}
return _myProperty;
}
}
这被称为懒惰实例化。
编辑:
private static SharedBrowser _shared;
public static SharedBrowser Shared {
get
{
var currentThreadId = GetCurrentThreadId();
if _shared == null) {
_shared = new SharedBrowser();
_sharedHwnd = _sharedBrowser.hWnd.ToString();
_sharedThreadId = currentThreadId;
}
if (currentThreadId != _sharedThreadId) {
_sharedBrowser = IE.AttachTo<SharedBrowser>(Find.By("hwnd", _sharedHwnd));
_sharedThreadId = currentThreadId;
}
return _shared;
}
}
静态构造函数的好处在于,您知道它在每个应用程序中只被调用一次。以后你就没有这种保证了。所以添加一个静态构造函数,并用Lazy<T>,然后在.get 中引用Lazy的.Value
存储一个私有类级别的SharedBrowser变量,然后在get块中检查其是否为null。然后,为了完成额外的初始化逻辑,将其重构到另一个方法中,并从get
和set
调用它。
private static SharedBrowser _shared = null;
private static SharedBrowser Shared
{
get
{
if(_shared == null)
{
_shared = new SharedBrowser();
InitSharedBrowser();
}
// the rest of your code here.
}
set
{
_shared = value;
InitSharedBrowser();
}
}
private static void InitSharedBrowser()
{
// your SharedBrowser Initialization logic goes here.
}