2017-06-19 17 views
0

的varibale我有一類constractor這樣緩存在構造函數C#

public class product_new : NK.Objects._product_new 
{ 
    private int Count_Per_Page; 
    public product_new(int count_per_page) 
    { 
     this.Count_Per_Page = count_per_page; 
    } 
    public int CountOP///////count of pages 
    { 
     get 
     { 
      return number_of_pages(Count_Per_Page); 
     } 
    } 

你看到CountOP是返回一個int值,它是連接到SQL數據庫返回該值。

private int number_of_pages(int tedad_per_pages) 
{ 
    return Q.Get_Back_Number_Of_Pages(
     tedad_per_pages, 
     tbl_name, 
     "", 
     new Queries.Cmd_Parameters()); 
} 

在如果從這個類CountOP沒有改變,但功能NUMBER_OF_PAGES創建對象幾個時間被釋放,並連接到SQL數據庫。

我該如何緩存這個變量?

+6

你的問題會容易得多,如果你閱讀」 d遵循常規的.NET命名約定。 –

+0

在您的代碼中添加以下行:private static字典 numberOfPages = new詞典();然後在你的方法中使用numberOfPages「number_of_pages」。 –

回答

0

嘗試使用static Dictionary<int, int> - 一個字典所有實例:

public class product_new : NK.Objects._product_new { 
    // Simplest, but not thread safe; use ConcurrentDictionary for thread safe version 
    private static Dictionary<int, int> s_KnownAnswers = new Dictionary<int, int>(); 

    // Lazy: do not execute expensive operation eagerly: in the constructor; 
    // but lazyly: in the property where we have to perform it 
    public int CountOP { 
     get { 
     int result = 0; 

     // do we know the answer? If yes, then just return it 
     if (s_KnownAnswers.TryGetValue(Count_Per_Page, out result)) 
      return result; 

     // if no, ask RDMBS 
     result = number_of_pages(Count_Per_Page); 

     // and store the result as known answer 
     s_KnownAnswers.Add(Count_Per_Page, result); 

     return result; 
     } 
    } 

    ... 
    } 
0

引入一個私有後臺字段,它保存值並在構造函數中初始化它的值。現在,您可以在您的getter中返回變量值,而不是在每次調用getter時觸擊數據庫。

public class product_new : NK.Objects._product_new 
{ 
    private int Count_Per_Page; 
    private readonly int _CountOP; 

    public product_new(int count_per_page) 
    { 
     this.Count_Per_Page = count_per_page; 
     this._CountOP = number_of_pages(count_per_page); 
    } 
    public int CountOP///////count of pages 
    { 
     get 
     { 
      return this._CountOP; 
     } 
    } 

除此之外,我強烈建議看看Mircrsofts naming-conventions

+0

@MattBurland完成,謝謝。 – HimBromBeere

-1

更改使用支持的房地產:

private int _npages = -1; 
public int CountOP///////count of pages 
    { 
     get 
     { 
      if(_npages == -1) 
       _npages = number_of_pages(Count_Per_Page); 
      return _npages; 
     } 
    } 
+1

或者使用'int?'並測試null。可以添加Nullables,這樣就不必使用「魔術」值來表示未初始化的值。 –

+0

那麼這個問題是你需要拋棄,或者在任何地方傳播可空類型的時候,當它清楚地使用-1作爲它位於屬性上方時。 – Steve

+1

不,你不知道。 '私人int? _npages',然後'public int CountOP'測試'_npages == null'並最終返回'_npages.Value'。消耗'CountOP'的代碼不需要知道或關心後臺字段是'int?'。而使用'_npages = -1',每個人都必須知道並關心(包括數據庫)'-1'是特殊的,不能在其他地方使用。 –