我觉得在面试中问这个有点荒谬。但如果面试官问..。需要回答。
解释的深度
致以敬意,
发布于 2011-09-04 19:35:50
要了解更多细节,您必须查看NHibernate源代码,但我的理解如下:延迟加载是通过使用在运行时生成的代理替换类来实现的。代理是从类继承的,因此它可以“拦截”方法调用并延迟加载实际数据。只有在方法和属性是虚拟的情况下,此拦截才能工作,因为客户端代码通过对类的引用调用它们。客户端代码可能不知道它真的使用代理(从类派生)的事实。实际的延迟加载逻辑要复杂得多,但大致上是这样的:
public class Customer {
public virtual String Name {
get { return _name; }
}
}
// code like this gets generated at runtime:
public class CustomerProxy7461293476123947123 : Customer {
private Customer _target;
public override String Name {
get {
if(_target == null){
_target = LoadFromDatabase();
}
return _target.Name;
}
}
}这样,只有当客户端实际调用“Name”时,数据才会被加载:
Customer customer = Session.Load<Customer>(1); // <-- proxy is returned
// or
Customer customer = salesman.FavoriteCustomer; // <-- proxy is returned
...
String name = customer.Name; // <-- proxy's Name will be called, loading data类似的机制用于集合,但不需要在运行时生成集合。NHibernate内置了延迟加载项的持久集合。
https://stackoverflow.com/questions/7299630
复制相似问题