创建使用数组对象C#的Session Helper类

时间:2015-02-28 12:07:47

标签: c# arrays session

我正在使用会话助手类来跟踪多个变量。到目前为止,我在页面之间需要30个,当然不是一次性的。我需要将一些值从单个转换为数组。我使用的Session helper类如下。为简洁起见,我只展示了两个会话变量,用于跟踪两个手风琴的制表符索引。

using System;
using System.Globalization;
using System.Linq;
using System.Web;

public class SessionHelper
{

    //Session variable constants
    public const string AccordionTop = "#tabTop";
    public const string AccordionBot = "#tabBot";


    public static T Read<T>(string variable)
    {
        object value = HttpContext.Current.Session[variable];
        if (value == null)
            return default(T);
        else
            return ((T)value);
    }

    public static void Write(string variable, object value)
    {
        HttpContext.Current.Session[variable] = value;
    }

    public static int TabTop
        {
            get
            {
                return Read<int>(AccordionTop);
            }
            set
            {
                Write(AccordionTop, value);
            }
        }

        public static int TabBot
        {
            get
            {
                return Read<int>(AccordionBot);
            }
            set
            {
                Write(AccordionBot, value);
            }
        }
}

因此,在每个页面上,我可以轻松地使用变量,如下所示:

To Write:
SessionHelper.TabTop = 1;  or  SessionHelper.TabBot = 3

To Read:
If (SessionHelper.TabTop……….)

一切正常。我现在想将它扩展到会话中保存的数组值。该数组包含int,string和date time值。 对于数组会话对象,我尝试添加:

    public class SessionHelper
    {

       public const string CompInfo = "CompAccInfo";

       public static T ReadArray<T>(string variable)
       {
            object[] result = HttpContext.Current.Session[variable] as object[];
            if (result == null)
            {
                return default(T);
                //result = new object[30];
            }
            else
                return ((T)(object)result);
        }

        public static void WriteArray(string variable, object[] value)
        {
            HttpContext.Current.Session[variable] = value;
        }   


public static object[] CompDetails
        {
            get
            {
                return ReadArray<object[]>(CompInfo);
            }
            set
            {
                WriteArray(CompInfo, value);
            }
        }
}

但是当我尝试这样做时,我得到一个“对象引用未设置为......错误:

    public void EGetCompanyInformation(MasterPage myMaster, int entityCode)
        {
            int prevEntity = 0;Using (sqlconnetiooo 
            .....
            //I get values here this works fine
            //Then:
            sqlr = cmd.ExecuteReader();
            sqlr.Read();
            if (sqlr.HasRows)
            {
                //Calculate accounting period adjustment.
                yearEndDiff = 12 - Convert.ToInt32(sqlr.GetDateTime(5).Month);

                    //Company Code.
                    SessionHelper.CompDetails[0] = sqlr.GetInt32(0);
                    //Company Name.
                    SessionHelper.CompDetails[1] = sqlr.GetString(1);
                    //Currency Unit.
                    SessionHelper.CompDetails[2] = sqlr.GetString(2);
                    //Base Currency Code.
                    SessionHelper.CompDetails[3] = sqlr.GetString(3);
                    //Reporting Currency Code.
                    SessionHelper.CompDetails[4] = sqlr.GetString(4);
                    //Company Year End.
                    SessionHelper.CompDetails[5] = yearEndDiff;
                    //Country Code.
                    SessionHelper.CompDetails[6] = sqlr.GetString(6);
                    //Country Name.
                    SessionHelper.CompDetails[7] = sqlr.GetString(7);
                    //Base Currency Name.
                    SessionHelper.CompDetails[8] = sqlr.GetString(8);
                    //Report Currency Name.
                    SessionHelper.CompDetails[9] = sqlr.GetString(9);
                    //ClientID.
                    SessionHelper.CompDetails[10] = sqlr.GetInt32(10);
Other code here
}

}

似乎任何SessionHelper.CompDetails [i]都不起作用:错误对象引用未设置为对象的实例。

3 个答案:

答案 0 :(得分:1)

如果ReadArray将返回默认值(T),会发生什么?它将返回null。比通过数组内的索引访问任何对象将导致您面临的异常。

您的代码打算做什么并不是很明显。

SessionHelper.CompDetails[0] = sqlr.GetInt32(0);

你想要什么? CompDetails本身应该返回一个数组。但是你试图用一些值立即重写它。

如果你想访问CompDetails并重写它的对象而不是你需要实例化它

int n = 10;
SessionHelper.CompDetails = new CompDetails[n];

答案 1 :(得分:0)

在开始为其分配值之前,必须先实例化CompDetails数组。

if (sqlr.HasRows)
{
    //Calculate accounting period adjustment.
    yearEndDiff = 12 - Convert.ToInt32(sqlr.GetDateTime(5).Month);

    // Instantiate array
    SessionHelper.CompDetails = new object[11];

    //Company Code.
    SessionHelper.CompDetails[0] = sqlr.GetInt32(0);

    // etc

答案 2 :(得分:0)

default(object[])将始终抛出null。因为对象数组是引用类型,任何引用类型的默认值都是null。因此,访问空值将为您提供Object reference not set to an instance of object

您可以更改旧的实施,如下所示:

public static T Read<T>(string variable, int arraySize=10)
{
    object value = HttpContext.Current.Session[variable];
    if(typeof(T).IsArray && value == null)
    {
      //array requires size I personally prefer to have
      //differnt read method for array.
      return ((T)Activator.CreateInstance(typeof(T),arraySize));
    }
    if(!typeof(T).IsValueType && value == null)
    {
        //if it is not value type you can return new instance.
        return ((T)Activator.CreateInstance(typeof(T)));
    }        
    else if (value == null)
        return default(T);
    else
        return ((T)value);
}

访问SessionHelper如下:

var sessionarray = SessionHelper.Read<object[]>("myarray",15);
....
// then use that sessionarray here.
....