一种调用方法一次的方法
本文关键字:方法 一次 一种 调用 | 更新日期: 2023-09-27 18:20:38
我有以下内容,我想将webDB和项的设置移动到以下public string method
之外,这是我如何进行此操作的示例。
public string Width
{
get
{
if (webDB != null)
{
webDB = Sitecore.Configuration.Factory.GetDatabase("web");
Sitecore.Data.Items.Item item = webDB.Items[StartItem];
if (item != null)
{
Sitecore.Data.Fields.Field field = item.Parent.Fields["Identity_Page_Width"];
if (!String.IsNullOrEmpty(field.Value))
{
return field.Value;
}
else
{
return "964"; // returns default pixel width if Identity_Page_Width is not defined, or is null
}
}
else
{
return "964"; // If item is not found return default width.
}
}
else
{
return "964";
}
}
}
这就是我试图将其分离的方式:
public void GetConfiguration()
{
if (webDB != null)
{
webDB = Sitecore.Configuration.Factory.GetDatabase("web");
if (item != null)
{
item = webDB.Items[StartItem];
}
}
}
但我一直在尝试在得到method must have a return type
的代码中运行该方法。
然后,我想在类中的某个地方只运行一次这个GetConfiguration,这样所有方法都不需要联系数据库和项目数据
我可以做MyClass class = New MyClass; Class.GetConfiguration();
,但我不想让未来的程序员知道每次都需要实例化才能继续。我宁愿消除这种依赖。
如果实例化的webDB
对类的大多数/所有功能都至关重要,请考虑在实例构造函数(如果是非静态的)或静态构造函数(如果为静态的)中初始化它
否则,我会创建一个
private InitializeWebDB(){if(webDB == null){...}}
需要时可以在课堂上调用。此外,对于需要访问此属性的属性,我会使用以下方法:
public String GetWidth(){InitializeDB(); ...}
这意味着比简单的属性字段返回更多的逻辑/开销。
您的代码可以通过以下几种方式进行改进。但为了回答你的问题-为什么不使用静态c'tor?这样可以确保它只运行一次
public class SomeClass
{
static SomeClass()
{
if (webDB != null)
// etc. etc.
}
... // other code
}
将webDB
变量设为static会强制要求它只在第一次Property调用中为null。
private static <whatevertype> webDB;
private static <whatevertype> item;
public void GetConfiguration()
{
if (webDB == null)
{
webDB = Sitecore.Configuration.Factory.GetDatabase("web");
if (item != null)
item = webDB.Items[StartItem];
}
}