C# 从其他名称空间强制转换错误
我正在尝试使用另一个会话中保存的列表 但是我得到了一个错误,因为列表模型是在另一个名称空间中创建的 无法将类型为“System.Collections.Generic.List1[OCC.CartItem]”的对象强制转换为类型为“System.Collections.Generic.List1[OCC.ShopCheckOut.CartItem]”的对象。C# 从其他名称空间强制转换错误,c#,list,model,casting,C#,List,Model,Casting,我正在尝试使用另一个会话中保存的列表 但是我得到了一个错误,因为列表模型是在另一个名称空间中创建的 无法将类型为“System.Collections.Generic.List1[OCC.CartItem]”的对象强制转换为类型为“System.Collections.Generic.List1[OCC.ShopCheckOut.CartItem]”的对象。 List<CartItem> cart = new List<CartItem>();
List<CartItem> cart = new List<CartItem>();
if (HttpContext.Current.Session["ShoppingCart" + HttpContext.Current.Session.SessionID] != null)
{
cart = (List<CartItem>)HttpContext.Current.Session["ShoppingCart" + HttpContext.Current.Session.SessionID];
}
List cart=new List();
if(HttpContext.Current.Session[“ShoppingCart”+HttpContext.Current.Session.SessionID]!=null)
{
购物车=(列表)HttpContext.Current.Session[“ShoppingCart”+HttpContext.Current.Session.SessionID];
}
有没有从其他名称空间使用模型的方法???您必须在两者之间进行转换-例如,使用
列表.ConvertAll
或LINQ
基本上,这两个类在名称空间中具有相同的短名称这一事实是无关的——它们实际上是完全不同的类
当然,如果您很乐意只使用会话中实际存在的类型,那也没关系,但是如果您确实想要一个列表
,则需要执行转换。如果
列表模型在另一个名称空间中创建
然后只使用该名称空间中的模型,而不是重新声明它:
List<ShopCheckOut.CartItem> cart = new List<ShopCheckOut.CartItem>();
if (HttpContext.Current.Session["ShoppingCart" + HttpContext.Current.Session.SessionID] != null)
{
cart = (List<ShopCheckOut.CartItem>)HttpContext.Current.Session["ShoppingCart" + HttpContext.Current.Session.SessionID];
}
List cart=new List();
if(HttpContext.Current.Session[“ShoppingCart”+HttpContext.Current.Session.SessionID]!=null)
{
购物车=(列表)HttpContext.Current.Session[“ShoppingCart”+HttpContext.Current.Session.SessionID];
}
或者反过来说
=>在一个合理的位置(甚至可能在它自己的名称空间内)声明你的
CartItem
类,并从那里在你的其他名称空间中使用它。我通过引用其他名称空间并从那里使用CartItem解决了这个问题