2012-01-16 131 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

相關問題