我懒惰地加载我的所有成员。我这样做已经有一段时间了,并且只是认为延迟加载从表面上看是一件好事。
假设我们有
public class SomeClass
{
public int anInt;
public SomeReferenceType member1;
public SomeClass()
{
//initialize members in constructor when needed (lazy load)
anInt = new int();
member1 = new SomeReferenceType();
}
}
这样做有什么缺点吗?这是正确的延迟加载模式吗?延迟加载值类型是否有意义(对于现代 RAM 甚至重要)?
After what I have learned from your answers, I would like to know if there is any difference between the above and this...
public class SomeClass
{
public int anInt;
public SomeReferenceType member1 = new SomeReferenceType();
public SomeClass()
{
}
}
首先,在构造函数内初始化成员不是延迟加载。
延迟加载是在第一次请求时初始化成员。 .NET 中的一个简单示例(带有一些双重检查锁定,因此我们不会遇到线程问题):
public class SomeClass
{
private object _lockObj = new object();
private SomeReferenceType _someProperty;
public SomeReferenceType SomeProperty
{
get
{
if(_someProperty== null)
{
lock(_lockObj)
{
if(_someProperty== null)
{
_someProperty= new SomeReferenceType();
}
}
}
return _someProperty;
}
set { _someProperty = value; }
}
}
幸运的是,如果您使用的是 .NET 4,您现在可以使用Lazy<T> Class它可以为您处理问题并使事情变得容易得多。
其次,当您有许多加载成本较高的成员并且您确定将使用所有这些值时,延迟加载是一个好主意。该成本将导致该类型的实例化速度不必要地缓慢。
仅仅为了延迟加载而进行延迟加载会给代码增加不必要的复杂性,如果做得不当(例如,在处理线程时),可能会导致问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)