问题
When I checked the implementation of Lazy<T>
class, I saw this block:
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
T obj = this.Value;
}
As you can see it's forcing initialization during serialization. Does anyone know why this behavior is preferred as default?
回答1:
if it doesnt and you provided lambda for initialization, where do you think it retrives the value on deserializing? lambdas are not serializable.
回答2:
The whole point of a Lazy<T>
is to delay evaluation until it's needed. This can save you processing power by not calculating things until you actually need to. When you serialise something, you generally want to serialise its value, so Lazy<T>
has to work out what that value is so that you can serialise it.
来源:https://stackoverflow.com/questions/17921035/why-lazyt-forces-initialization-during-serialization