Why Lazy<T> forces initialization during serialization?

安稳与你 提交于 2020-08-07 06:11:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!