微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

延迟初始化 (Lazy<T>) 或带有支持字段的属性

如何解决延迟初始化 (Lazy<T>) 或带有支持字段的属性

据微软称,

一个对象的延迟初始化意味着它的创建被推迟 直到第一次使用为止。 (对于本主题,术语惰性初始化 和延迟实例化是同义词。)延迟初始化是 主要用于提高性能,避免浪费计算,以及 减少程序内存需求。

假设我有一个Product类和一个Category类,并且关系是一对多的,也就是说一个Product对象持有一个Category对象,一个Category对象持有一个集合产品对象。

这是Product类的代码

class Product
{
    public string Code { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }

    public Category Category { get; set; }
} 

这是 Category 类的代码

class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }

    public ICollection<Product> Products { get; private set; }
}

在这种情况下,Category 对象的 Product 对象并不总是需要的,因此并不总是需要对其进行初始化。所以,这就是我所做的:

class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }

    public ICollection<Product> products;
    public ICollection<Product> Products
    {
        get
        {
            if (products == null)
            {
                // retrieves the products from the database and stores it in field: products
            }
            return products;
        }
    }
}

通过这样做,产品会被检索一次,并且仅在被要求时才检索,对吗?然后,我阅读了 Lazy Initialization,并像这样起草了我的 Category 类:

class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }

    public ICollection<Product> products;
    public Lazy<ICollection<Product>> Products => new Lazy<ICollection<Product>>(() => GetProductsByCategoryID(this.CategoryID));

    public ICollection<Product> GetProductsByCategoryID(int categoryID)
    {
        // retrieves the products from the database
    }
}

我的问题是,这两种实现方式有何不同?延迟初始化是提供更好的性能还是使用更少的内存?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。