2013-09-24 22 views
1

我試了兩天谷歌搜索,但似乎無法找到答案。何處/何時填充查找值?

我想讓Category類根據輸入的id提供描述,並在id無效時返回一個錯誤。這是最好的方法嗎?

public class Category 
{ 
    private int _id; 
    private string _desc; 

    public Category(int id) 
    { 
     ID = id; 
    } 

    public int ID 
    { 
     get 
     { 
      return _id; 
     } 

     set 
     { 
      _id = value; 

      //_desc = value from data access layer or throw error if the ID is invalid    
     } 
    } 

    public string Description 
    { 
     get 
     { 
      return _desc; 
     }  
    } 
} 

public class Person 
{ 
    public int ID {get; set;} 

    public Category Category {get; set;} 
} 

public class MyApp 
{ 
    static void Main() 
    { 
     Person p = new Person(); 

     Category c = new Category(2); 

     p.Category = c; 
    } 
} 
+0

你會從哪裏獲得這些查找值?他們是硬編碼的嗎? –

+0

不,他們將被存儲在數據庫中 – Tom

回答

2

由於可能有幾個類別的實例,因此將查找值包含在類本身中會浪費記憶。相反,他們應該訪問其他地方。例如另一個類中的靜態函數。

public class CategoryHelper 
{ 
    public static string GetCategoryDesc(int CatgeoryId) 
    { 
     ...access database to get description 
    } 
} 

其中我們可以在說明吸氣劑的範疇類使用:

public string Description 
{ 
    get 
    { 
     return CategoryHelper.GetCategoryDesc(this.ID); 
    }  
} 

現在,因爲我們在一個單獨的類有GetCategoryDe​​sc我們現在可以優化其性能。例如,如果您確信查詢的值在運行期間不會更改,則可以將描述緩存在內存中以避免數據庫跳轉。在下面的代碼中,我們只在第一次調用數據庫時調用數據庫,並且結果被緩存。這被稱爲「memoization」。

public class CategoryHelper 
{ 
    Dictionary<int,string> cachedDesc; //Dictionary used to store the descriptions 
    public static string GetCategoryDesc(int CatgeoryId) 
    { 
     if (cachedDesc==null) cachedDesc = new Dictionary<int,string>(); // Instatiate the dictionary the first time only 
     if(cachedDesc.ContainsKey(CatgeoryId)) //We check to see if we have cached this value before 
     { 
      return cachedDesc[CatgeoryId]; 
     } 
     else 
     { 
      var description = .... get value from DB 
      cachedDesc.add(CatgeoryId, description); //Store the value for later use 
      return description; 
     } 
    } 
} 

可以讓這個更簡單,更復雜,因爲它是在其自身的功能分離出來,你將不得不這樣做幾乎沒有變化別處。

+0

非常感謝!說得通。 – Tom

+0

@Tom - 很高興爲您提供幫助。如果您覺得它有助於您,請不要忘記接受這個答案。祝你好運! –