我有一个类跟这样的约束
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数据库。
如何缓存此变量?
答案 0 :(得分: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。
答案 1 :(得分: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;
}
}
...
}
答案 2 :(得分:-1)
更改为使用支持的属性:
private int _npages = -1;
public int CountOP///////count of pages
{
get
{
if(_npages == -1)
_npages = number_of_pages(Count_Per_Page);
return _npages;
}
}