问题描述
当我为会话创建对象时,它抛出了运行时错误,即
Hi,
When I am creating a object for a session, it was throwing me a run time error i.e.
Unable to cast object of type 'System.Collections.Generic.List`1[RACS.Completion.Web.Private.Activity.Service]' to type 'RACS.Completion.Web.Private.Activity.Service'.
我的代码是这样的:
My code is like this:
Service obj = new Service();
obj = (RACS.Completion.Web.Private.Activity.Service)Session["obj"];
任何人都可以帮忙.
问候,
Basha.s
Can anyone help on this.
Regards,
Basha.s
推荐答案
Service obj = new Service();
带有:
With:
RACS.Completion.Web.Private.Activity.Service obj = new RACS.Completion.Web.Private.Activity.Service()
Service obj = new Service();
obj = (RACS.Completion.Web.Private.Activity.Service)(Session["obj"]);
或者,检查Session ["obj"]的返回值是Service,因为错误消息暗示它是Session [].
顺便说一句:在构造变量时总是创建一个新对象来填充变量是个坏主意,特别是当您要立即替换其内容时.它浪费了内存,并可能浪费了对象构造函数中的其他资源.要么将其保留为空,要么在进行初始分配时创建它(在示例中为Session)
Alternatively, check that the Session["obj"] return value is a Service, as the error message implies it is a Session[] instead.
BTW: It is a bad idea to always create a new object to fill a variable when you construct it - particularly when you are going to replace it''s content immediately. It wastes memory, and possibly other resources in the object constructor. Either leave it null, or create it when you do the initial assignment (from Session in your example)
List<service></service>
中具有
Session["obj"]
.
最好尝试这样的事情:
.
It''s better to try something like that:
if(Session["obj"]!=null)
{
var objList=Session["obj"] as List<racs.completion.web.private.activity.service>;
var objRes=objRes!=null ? objList.FirstOrDefault() : new racs.completion.web.private.activity.service();
if(objRest!=null) ..
}
</racs.completion.web.private.activity.service>
之后,您应该考虑-为什么要使用List< racs.completion.web.private.activity.service>在Session ["obj"]中,而不是在RACS.Completion.Web.Private.Activity.Service中,否则以后您会遇到新的问题.
After that you should think - why you have List<racs.completion.web.private.activity.service> in Session["obj"] and not RACS.Completion.Web.Private.Activity.Service, or you''ll have new problems later.
这篇关于创建对象时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!