2017-06-19 37 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'是特殊的,不能在其他地方使用。 –