序列化组合函数?

发布于 2024-09-17 06:24:36 字数 580 浏览 5 评论 0原文

这工作正常:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲鸠 2024-09-24 06:24:36

第二种情况发生的是涉及闭包。在 func2 内部使用 func1 创建一个闭包来捕获 lambda 表达式之间的共享状态。闭包不可序列化。当您尝试序列化 func 时,它会尝试序列化作为闭包的目标对象,并且您会得到异常。

What's happening in the second case is that a closure is involved. The use of func1 inside of func2 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文