关注开源代码的实际应用
PostSharp4ViewState是PostSharp的一个插件,用于简化Asp.Net页面与控件的状态管理。如果需要将页面或控件中的 字段或属性值保存在ViewState或ControllState中,以便在页面Postback后仍可取得,只需在相应的字段或属性上添加 PersistAttribute特性的声明。
PostSharp4ViewState的主要组件为一个用于搜寻声明了PersistAttribute的字段和属性的AdviceProvider,对于搜寻到字段和属性以如下方式进行织入:
如果字段或属性被配置为存储于ViewState,则创建或修改LoadViewState与SaveViewState;如果字段或属性被配置为存储于 ControlState,则创建或修改 LoadControlState与SaveControlState,同时如果没有OnInit方法则创建一个同时添加 Page.RegisterRequiresControlState(this)调用。
处理ViewState 与 ControlState 存储的方法除了名称不同外其它的都一样,并按以下进行代码生成:
If Save*State method exists new code is added after existing. It stores values of decorated fields/properties in object[] array and puts it together with resut of existing code in another object[] array
If Save*State method doesn't exist it is generated as if it existed and contained only a call to base.Save*State
If Load*State method exists new code is added before existing. It casts passed value to object[] array and uses second element (casted as another object[]) to initiate decorated fields/properties. First value is passed to existing code
If Load*State method does't exist it is generated as if it existed and contained only a call to base.Load*State
例子:
- public class Properties : BaseControl
- {
- private int _intValue;
- [Persist(Mode = PersistMode.ControlState)]
- public int IntProp
- {
- get { return _intValue; }
- set { _intValue = value; }
- }
- }
相应编译后的内容为:
- public class Properties : BaseControl
- {
- private int _intValue;
- protected override void LoadControlState(object A_1)
- {
- object[] ~tmp~0 = (object[]) A_1;
- object[] ~tmp2~1 = (object[]) ~tmp~0[1];
- if (~tmp2~1[0] != null)
- {
- this.IntProp = (int) ~tmp2~1[0];
- }
- A_1 = ~tmp~0[0];
- base.LoadControlState(A_1);
- }
- protected override void OnInit(EventArgs A_1)
- {
- this.Page.RegisterRequiresControlState(this);
- base.OnInit(A_1);
- }
- protected override object SaveControlState()
- {
- object ~tmpOldValue~1 = base.SaveControlState();
- object[] ~tmp~0 = new object[] { this.IntProp };
- return new object[] { ~tmpOldValue~1, ~tmp~0 };
- }
- [Persist(Mode=PersistMode.ControlState)]
- public int IntProp
- {
- get
- {
- return this._intValue;
- }
- set
- {
- this._intValue = value;
- }
- }
- }
由于是编译期代码生成,只是在编译结果中插入用于存储属性值的代码,所以PostSharp4ViewState代码性能与手写代码性能一样。可以通过Reflector反编译结果程序集来进行检查。