“无法将’System.Byte ‘类型的对象强制转换为’System.IConvertible’。”照片中的错误:为什么以及如何修复它?

我下面的代码给出错误“无法将类型’System.Byte []’的对象强制转换为’System.IConvertible’。”

protected void btnSubmit_Click(object sender, EventArgs e) { if (fpPhoto.HasFile) { if (fpPhoto.PostedFile.ContentType == "image/jpg" || fpPhoto.PostedFile.ContentType == "image/jpeg" || fpPhoto.PostedFile.ContentType == "image/png") { int filelenght = fpPhoto.PostedFile.ContentLength; imagebytes = fpPhoto.FileBytes; //fpPhoto.PostedFile.InputStream.Read(imagebytes, 0, filelenght); } } User objUser = new User(); objUser.UserName_Pk = txtUserName.Text; objUser.Password = txtPassword.Text; objUser.MobileNo = txtMobileNo.Text; objUser.Email = txtEmail.Text; objUser.SecurityAnswer = txtAnswer.Text; objUser.Photo = Convert.ToByte( imagebytes); 

为什么我会收到此错误,如何解决?

我假设imageBytes是一个字节数组( byte[] )。 在您的代码编译时, Photo属性必须是byte类型。 您尝试将字节数组转换为此行中的单个字节:

 objUser.Photo = Convert.ToByte( imagebytes); 

这导致exception,因为字节数组不实现IConvertible ,这是转换工作所必需的。 但是你想如何将字节数组转换为单个字节呢? 转换机制应该如何知道要分配给单个字节的数组的哪个字节? 因此,我怀疑你更希望Photo属性也是byte[]类型,这样它才能存储完整的图片,而不仅仅是它的一个字节。

因此,为了解决这个问题,请尝试将实体中的属性更改为byte[] (这可能还涉及更改数据库模式)并直接分配数组,而不使用Convert.ToByte()