2012-01-16 145 views
0

我有以下,我想移动以下public string method以外的webDB和项目的设置,这是一个例子,我将如何去做这件事。一种方法调用方法一次

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();但我不希望未来的编码人员必须知道这需要每次都要实例化以继续。我宁愿删除这种依赖。

回答

1

如果webDB被实例是类的大多数/所有功能至关重要,考虑在实例构造函数初始化它(如果非静态),或静态构造函数(如果静态)

否则,我会创建一个

private InitializeWebDB(){if(webDB == null){...}} 

您可以在您的班级内需要时调用。 此外,在其上需要访问这个属性,我会使用方法,而不是如:

public String GetWidth(){InitializeDB(); ...} 

这意味着更多的逻辑/开销比一个简单的属性字段的回报。

+0

完美的构造函数哈哈,叹了口气我应该重新阅读基本的编程书IDE的Web开发正在让我忘记了基本知识。 – Anicho 2012-01-16 14:46:06

1

您的代码可以通过几种方式进行改进。但要回答你的问题 - 为什么不使用静态c'tor?这样可以确保它只有一次

public class SomeClass 
{ 
    static SomeClass() 
    { 
     if (webDB != null) 
     // etc. etc. 
    } 
    ... // other code 
} 
+0

只有当webDB是静态的(我们不知道) – Erix 2012-01-16 14:27:46

+0

@Erix - 这是真的,谢谢你。我认为这是错误的,基于webDB = Sitecore.Configuration.Factory.GetDatabase(“web”);' @Anicho - 请让我知道你是否需要webDB是非静态的。 – Jonno 2012-01-16 14:32:47

+0

'item = webDB.Items' this returns on [StartItem]'对象引用对于非静态字段,方法或属性是必需的'我努力使StartItem静态。 – Anicho 2012-01-16 14:36:15

1

使得webDB静态变量会强加,它只会在你的第一个属性调用空运行。

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]; 
    } 
} 
+0

与Jonno StartItem requries相同的问题参考。 – Anicho 2012-01-16 14:39:11

+1

+1帮助我走向正确的方向。 – Anicho 2012-01-16 14:46:32