序列化组合函数?
这工作正常:
Func<string, string> func1 = s => s + "func";
ViewState["function"] = func1;
但是,这不行:
Func<string, string> func1 = s => s + "func";
Func<string, string> func2 = s => func1(s);
ViewState["function"] = func2;
它抛出运行时序列化异常:Type 'MyProjectName._Default+<>c__DisplayClass3' in Assembly 'MyProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ' 未标记为可序列化。
现在,我可以解决这个问题,但我想了解为什么会发生这种情况,以便将来我别无选择,只能在序列化之前组合函数,我会有一个解决方案。
This works fine:
Func<string, string> func1 = s => s + "func";
ViewState["function"] = func1;
However, this does not:
Func<string, string> func1 = s => s + "func";
Func<string, string> func2 = s => func1(s);
ViewState["function"] = func2;
It throws a runtime serialization exception: Type 'MyProjectName._Default+<>c__DisplayClass3' in Assembly 'MyProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
Now, I can work around this this time, but I'd like to understand why this is happening so that if, in the future, I have no choice but to compose functions before serialization, I'll have a solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第二种情况发生的是涉及闭包。在
func2
内部使用func1
创建一个闭包来捕获 lambda 表达式之间的共享状态。闭包不可序列化。当您尝试序列化 func 时,它会尝试序列化作为闭包的目标对象,并且您会得到异常。What's happening in the second case is that a closure is involved. The use of
func1
inside offunc2
creates a closure to captured the shared state between the lambdas expressions. Closures are not serializable. When you try and serialize the func it tries to serialize the target object which is the closure and you get your exception.