本文介绍了当Session [& quot; something&]]引发NullReferenceException时,如何自动调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在我的应用程序中大量使用Session["firmaid"].当有人登录到我的系统时,将设置此值.

I am going to be using Session["firmaid"] quite alot in my application. This value is set when someone logs in to my system.

如果发生某种情况,并且该值从Session中丢失,我想以某种方式拥有一个全局方法,如果该方法抛出NullReferenceException.

If something happens, and this value is lost from the Session, i would like to somehow have a global method that will get it, if it throws a NullReferenceException.

我该怎么做?

当前,我的解决方案是每次使用Session["firmaid"]时都尝试捕获,然后执行将Firmaid放入Session的方法(如果抛出Exception的话).

Currently, my solution is to try and catch every time i use Session["firmaid"], then execute the method that will put firmaid in the Session, if it throws an Exception.

有更简单的方法吗?

推荐答案

您不必每次都尝试/捕获,而可以将对会话的访问权包装在强类型的类中,然后通过此包装器访问会话.

Instead of try/catching everytime you could wrap the access to the session in a strongly typed class and then access the session through this wrapper.

甚至编写扩展方法:

public static class SessionExtensions
{
    public static string GetFirmaId(this HttpSessionStateBase session)
    {
        var firmaid = session["firmaid"] as string;
        if (string.IsNullOrEmpty(firmaid))
        {
            // TODO: call some method, take respective actions
        }      
        return firmaid;
    }
}

,然后在您的代码中代替:

and then in your code instead of:

try
{
    var firmaid = Session["firmaid"];
    // TODO: do something with the result
}
catch (Exception ex)
{
    // TODO: call some method, take respective actions
}

使用:

var firmaid = Session.GetFirmaId();
// TODO: do something with the result

这篇关于当Session [& quot; something&]]引发NullReferenceException时,如何自动调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 05:19