日期:2014-05-17  浏览次数:20760 次

请问一个泛型转换的问题
本帖最后由 wggfcusmq 于 2013-11-22 11:46:20 编辑
private static T GetParametersValue<T>(string paraname, object defaultvalue)
        {
            if (HttpContext.Current.Session == null)
            {
                DataTable dt_para = new SDERP.BLL.SysManage.Sys_Parameters().GetList("PID='" + paraname + "'");
                if (dt_para.Rows.Count != 0)
                    HttpContext.Current.Session = dt_para.Rows;
                else
                    HttpContext.Current.Session = defaultvalue;
            }

            if (typeof(T) == typeof(bool))
            {
                return (T)((object)(Convert.ToInt32(HttpContext.Current.Session.ToString()) == 1));
            }
            else
                return (T)HttpContext.Current.Session[paraname];
        }


我有上面这个方法,当T为int,HttpContext.Current.Session[paraname]的值为"100"时,语句return (T)HttpContext.Current.Session提示"指定的转换无效"的错误,请问这是什么原因呢?该怎么解决。

------解决方案--------------------
HttpContext.Current.Session[paraname]这里面是字符串。
字符串不能强制转化成int。必须借助Convert.ToInt32()这一类的方法。

如果T是int型的话,HttpContext.Current.Session[paraname]应该存放整数100,这样就可以直接转了