System.InvalidCastException in

本文关键字:in InvalidCastException System | 更新日期: 2023-09-27 17:49:36

 System.InvalidCastException: [A]System.Collections.Generic.List`1[UploadImages] cannot be cast to [B]System.Collections.Generic.List`1[UploadImages].
  if (ViewState["CurrentList"] != null)
            {
        ObjUpload.AddRange((List<UploadImages>)ViewState["CurrentList"]); // Getting the above error  
            }

UploadImages ObjUp = new UploadImages();

    List<UploadImages> ObjUpload = new List<UploadImages>();
    ObjUp.AlternateText = TxtAlternatetext.Text;
    if (TxtFre.Text != "")
    {
        ObjUp.frequency = Convert.ToInt16(TxtFre.Text);
    }
    ObjUp.ImageURL = FileUpload1.PostedFile.FileName;
    ObjUp.URL = TxtUrlToNavigate.Text;
    ObjUp.ID = i;
    ObjUpload.Add(ObjUp);

我已经创建了我的类[Serializable]

这段代码有时工作,但有时不工作

System.InvalidCastException in

使用as运算符确保:

List<UploadImages> uploadImages = ViewState["CurrentList"] as List<UploadImages>;
if(uploadImages != null)
{
    ObjUpload.AddRange(uploadImages); 
}