我的一段代码如下
Session["tt"] = DateTime.Now.ToString();
Response.Write(Session["tt"].ToString());
DateTime dtmLastSendTime = (DateTime)System.Web.HttpContext.Current.Session["tt"];
上面的代码运行到最后一句时报错.
但是换成
DateTime dtmLastSendTime = Convert.ToDateTime(System.Web.HttpContext.Current.Session["tt"]);
就没有问题
Convert.ToDateTime和(DateTime)这两中类型转换方式有区别吗
Session["tt"] = DateTime.Now.ToString();
Response.Write(Session["tt"].ToString());
DateTime dtmLastSendTime = (DateTime)System.Web.HttpContext.Current.Session["tt"];
上面的代码运行到最后一句时报错.
但是换成
DateTime dtmLastSendTime = Convert.ToDateTime(System.Web.HttpContext.Current.Session["tt"]);
就没有问题
Convert.ToDateTime和(DateTime)这两中类型转换方式有区别吗
但Convert则不见得,它会根据当前参数里的类型/对象,做解析(parse)或数据转换,譬如下面能成功
int i = Convert.ToInt32("123");
但下面不会成功
object o = "123";
int i = (int)o; //运行时会出错
ConvertToDateTime(object): 类型转换, object不一定与DateTime兼容. 如: object可以是字符串, 如: "2008-10-10"
这种叫强制转换.
但Convert则不见得,它会根据当前参数里的类型/对象,做解析(parse)或数据转换,譬如下面能成功
int i = Convert.ToInt32("123");
但下面不会成功
object o = "123";
int i = (int)o; //运行时会出错