I think it's a little bit ridiculous to ask that in an interview. But if the interviewer ask ... need to answer.
Explain in depth:
- why properties and method must be virtual
- how lazy loading works
Reg开发者_开发问答ards,
You will have to look at NHibernate source code for more details, but my understanding is following: lazy loading is implemented by substituting a class with a proxy generated at runtime. Proxy is inherited from the class, so that it can 'intercept' method calls and load the actual data lazily. This interception would only work if methods and properties are virtual, because the client code calls them through a reference to the class. Client code can be unaware of the fact that it really uses a proxy (derived from the class). The actual lazy loading logic is a lot more complex but this is roughly what is going on:
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;
}
}
}
This way the data would only get loaded when client actually calls '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
Similar mechanisms are used for collections except that collections don't need to be generated at runtime. NHibernate has built-in persistent collections that load items lazily.
精彩评论