Application [“Key”]和Application.Contents [“Key”]有什么区别?

时间:2010-03-08 17:14:29

标签: c# asp.net

Application["temp"] = 8;应将值8设置为键temp

然而,Application.Contents["temp"] = 8;

也是如此

那么这两者之间有什么区别?

非常感谢。

2 个答案:

答案 0 :(得分:4)

“内容”属性的目的只是返回reference to the HttpApplicationState object

它只返回this,所以你理论上可以做Application.Contents.Contents.Contents.Contents["temp"] = 8;,它会做同样的事情。

只需使用Application["temp"] = 8;

答案 1 :(得分:3)

Contents属性是Application的默认属性,因此当您使用:

Application["temp"] = 8;

在引擎盖下,上述代码将更改为调用Application.Contents["temp"] = 8

编辑:我刚刚使用了Reflector,正如Greg指出的那样,Contents属性只返回当前HttpApplicationState对象的引用。在这种情况下,不确定我的答案是否严格正确 - 有人可以验证吗?

编辑:好的,我发现当你调用Application["temp"] = 8;Application.Contents["temp"] = 8;时,它实际上调用了HttpApplicationState.Item。看看这个IL:

.method family hidebysig instance void Page_Load(object sender, class [mscorlib]System.EventArgs e) cil managed
{
    .maxstack 8
    L_0000: nop 
    L_0001: ldarg.0 
    L_0002: call instance class [System.Web]System.Web.HttpApplicationState [System.Web]System.Web.UI.Page::get_Application()
    L_0007: ldstr "Key"
    L_000c: ldc.i4.8 
    L_000d: box int32
    L_0012: callvirt instance void [System.Web]System.Web.HttpApplicationState::set_Item(string, object)
    L_0017: nop 
    L_0018: ldarg.0 
    L_0019: call instance class [System.Web]System.Web.HttpApplicationState [System.Web]System.Web.UI.Page::get_Application()
    L_001e: callvirt instance class [System.Web]System.Web.HttpApplicationState [System.Web]System.Web.HttpApplicationState::get_Contents()
    L_0023: ldstr "Key"
    L_0028: ldc.i4.8 
    L_0029: box int32
    L_002e: callvirt instance void [System.Web]System.Web.HttpApplicationState::set_Item(string, object)
    L_0033: nop 
    L_0034: ret 
}