By definition virtual properties or methods are methods visible to sub classes to be overridden. But, NHibernate for example uses virtual properties to ensure lazy loading.
My question is not about NHibernate, but how you could use virtual properties to achieve lazy loading? Are there any hidden behaviors about virtual properties that I don't know?
The fact that they are declared virtual allows NHibernate to override the property and create a proxy implementation for it - the proxy in turn they can use to implement lazy loading on the first access of the property.
There is no hidden behavior behind virtual
members. Except the not so hidden fact that they can be overridden in child classes.
Lazy loading can be achieved by using the Lazy<T>
class. In which T is the type that will be loaded. It'll implicitly convert to T
.
Or if you want to manually set properties to behave lazy you could use something like this:
private SomeType _someProperty = null;
public override SomeType SomeProperty
{
get
{
if (_someProperty == null)
{
// Load _someProperty
}
return _someProperty;
}
}
With ValueTypes you can choose to make them Nullable<T>
. Or introduce a bool
whether they're loaded or not.
来源:https://stackoverflow.com/questions/8828077/virtual-properties-and-lazy-loading