闽公网安备 35020302035485号
延迟初始化 是一种将对象的创建延迟到第一次需要用时的技术,换句话说,对象的初始化是发生在真正需要的时候才执行,值得注意的是,术语 延迟初始化 和 延迟实例化 的意思是相同的——可以互换使用,通过使用 延迟初始化 技术,可以避免应用程序不必要的计算和内存消耗,这篇文章我们将会讨论如何在 C# 中使用 延迟初始化。
Lazy<IEnumerable<Order>> orders = new Lazy<IEnumerable<Order>>(); IEnumerable<Order> result = lazyOrders.Value;
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public List<Blog> Blogs { get; set; }
}
public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime PublicationDate { get; set; }
}
public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public Lazy<IList<Blog>> Blogs => new Lazy<IList<Blog>>(() => GetBlogDetailsForAuthor(this.Id));
private IList<Blog> GetBlogDetailsForAuthor(int Id)
{
//Write code here to retrieve all blog details for an author.
}
}
public sealed class StateManager
{
private StateManager()
{
}
public static StateManager Instance
{
get
{
return Nested.obj;
}
}
private class Nested
{
static Nested()
{
}
internal static readonly StateManager obj = new StateManager();
}
}
public class StateManager
{
private static readonly Lazy<StateManager> obj = new Lazy<StateManager>(() => new StateManager());
private StateManager() { }
public static StateManager Instance
{
get
{
return obj.Value;
}
}
}
可以瞄一下上面代码的 Instance 属性,它被做成只读属性了,同时也要注意 obj.Value 也是一个只读属性。 public class Lazy<T>
{
public T Value
{
get
{
if (_state != null)
{
return CreateValue();
}
return _value;
}
}
}
延迟初始化 是一个很不错的性能优化技术,它允许你将那些 资源密集型 的对象延迟到你真正需要加载的时候再加载,大家结合自己的场景尽情的使用吧!