public static void AddToSession(string key, Model.GenericDeliveryGroup model)
        {
            List<Model.GenericDeliveryGroup> list = new List<Model.GenericDeliveryGroup>();
            if (System.Web.HttpContext.Current.Session[key] != null)
            {
                list = (List<Model.GenericDeliveryGroup>)System.Web.HttpContext.Current.Session[key];
                list.Add(model);
                System.Web.HttpContext.Current.Session[key] = list;
            }
            else
            {
                list.Add(model);
                System.Web.HttpContext.Current.Session[key] = list;
            }
        }        public static void UpdateList(string key, List<Model.GenericDeliveryGroup> list)
        {
            System.Web.HttpContext.Current.Session[key] = list;
        }以上是将对象数据临时存入Session的方法,如果有n个对象,要分别n个这种存储更新删除的方法了,能否只定义一次,可以多个对象使用,例如以下的伪代码: public static void AddToSession(string key, object obj)
        {
            List<object> list = new List<object>();
            if (System.Web.HttpContext.Current.Session[key] != null)
            {
                list = (List<object>)System.Web.HttpContext.Current.Session[key];
                list.Add(obj);
                System.Web.HttpContext.Current.Session[key] = list;
            }
            else
            {
                list.Add(obj);
                System.Web.HttpContext.Current.Session[key] = list;
            }
        }

解决方案 »

  1.   

    用泛型方法或者泛型类做
    public static void AddToSession<T>(string key, T model)
    {
      List<T> list = new List<T>();
      if (System.Web.HttpContext.Current.Session[key] != null)
      {
      list = (List<T>)System.Web.HttpContext.Current.Session[key];
      list.Add(model);
      System.Web.HttpContext.Current.Session[key] = list;
      }
      else
      {
      list.Add(model);
      System.Web.HttpContext.Current.Session[key] = list;
      }
    }public static void UpdateList<T>(string key, List<T> list)
    {
      System.Web.HttpContext.Current.Session[key] = list;
    }
      

  2.   

    请问GetList如何用泛型写? public static object GetListbySession(string key)
            {
                if (System.Web.HttpContext.Current.Session[key] != null)
                {
                    return System.Web.HttpContext.Current.Session[key];
                }
                else
                {
                    return null;
                }        }
      

  3.   

    public static T GetListbySession<T>(string key)
      {
      if (System.Web.HttpContext.Current.Session[key] != null)
      {
      return (T)System.Web.HttpContext.Current.Session[key];
      }
      else
      {
      return default(T);
      }
      }
      

  4.   

    调用时这样写?
    List<Model.GenericDeliveryGroup> list = SessionHelper.GetListbySession<List<Model.GenericDeliveryGroup>>("DELIVERY_GROUPS");貌似有点怪异,平时没用过多少泛型。。
      

  5.   

    就是那么写,你<>里写的是什么类型,最后得到的就是什么类型。