Asp.net:可以将委托(“动作”)序列化为控制状态吗? [英] Asp.net: Can a delegate ("Action") be serialized into control state?

查看:67
本文介绍了Asp.net:可以将委托(“动作”)序列化为控制状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个用户控件,该控件具有将Action委托作为参数的方法。

I am implementing a user control that has a method that takes an Action delegate as a parm.

尝试将委托存储在Control State中会产生序列化错误。

Attempting to store the delegate in Control State yields a serialization error. Is it even possible to serialize a delegate into Control State?

BP

推荐答案

不容易-可能会打开潜在问题的大门。

Not easily - and it could open the door for potential problems.

从理论上讲,可以使用反射来确定委托调用对象的哪种方法,并为其编写自定义序列化过程。反序列化后,您将再次需要编写逻辑以将信息转换为委托引用。

It is theoretically possible to use reflection to determine which method of an object the delegate is invoking, and write a custom serialization process for it. Upon deserialization you would once again need to write logic to convert the information into a delegate reference.

问题是,在一般情况下,在运行时发现对象不一定总是需要重新生成委托。如果委托人引用的lambda或匿名方法使事情变得更加复杂,因为它们可能涉及到闭包。

The problem is that in the general case, discovering the object at runtime that you need to re-generate the delegate for is not always possible. If the delegate refers to a lambda or anonymous method that complicates things even more because their may be closures involved.

您可能会更好:


  1. 在请求之间不保留Action委托,并且使ASP.NET代码在回发时重新附加该委托。这是风险最小的选项恕我直言。

  1. Not preserving the Action delegate between requests and having the ASP.NET code re-attach the delegate on postback. This is the least risky option IMHO.

以会话状态存储委托引用,并在回发时将其重新附加到反序列化的对象上。此选项有风险,其原因有两个:

Storing the delegate reference in session state and reattach it to the deserialized object on postback. This option is risky for two reasons:

a)如果最终用户从不回发,或者您忘记从服务器清除对象,则无限期地保留对象引用在内存中州。

a) holding on to object references indefinitely in memory if the end user never posts back, or you forget to clear the object from server state.

b)如果委托引用了页面元素(控件等),则您可能会将
运行到细微的错误中,因为委托将对上一个请求,而不是新请求。

b) if the delegate references page elements (controls, etc) you may run into subtle bugs because the delegate will operate against the objects from the previous request, and not the new request.

这篇关于Asp.net:可以将委托(“动作”)序列化为控制状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆