填充查找值的位置/时间



我已经尝试了两天的谷歌搜索,但似乎找不到答案。

我希望 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;
    }
}

由于类类别可能有多个实例,因此在类本身中包含查找值将浪费内存。相反,应该在其他地方访问它们。例如,另一个类中的静态函数。

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

我们可以在类别类的描述获取器中使用:

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

现在,由于我们将 GetCategoryDesc 放在一个单独的类中,我们现在可以优化它的性能。例如,如果您相当确定查找的值在运行期间不会更改,则可以将描述缓存在内存中以避免数据库行程。在下面的代码中,我们仅在第一次调用并缓存结果时调用 DB。这称为"记忆"。

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;
        }
    }
}

您可以使其更简单,甚至更复杂,并且由于它自己的功能是隔离的,因此您几乎不必在其他地方进行任何更改。

最新更新