开发者

Serialize Composed Func?

This works fine:

    Func<string, string> func1 = s => s + "func";
    ViewState["function"]开发者_如何学Python = 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜