"无法投类型的对象'System.Byte []'键入'System.IConvertible'&QUOT。错误照片:为什么和如何解决呢? [英] "Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible'." error in Photo: why and how do I fix it?

查看:167
本文介绍了"无法投类型的对象'System.Byte []'键入'System.IConvertible'&QUOT。错误照片:为什么和如何解决呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的code给出了错误无法投类型的对象'System.Byte []'键入'System.IConvertible'。

My code below gives the error "Unable to cast object of type 'System.Byte[]' to type '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);  

为什么会出现这个错误,我怎么能解决这个问题?

Why do I get this error, and how can I fix it?

推荐答案

我认为 imageBytes 是一个字节(数组字节[] )。当你的code编译,在照片属性必须是类型字节的。您尝试将字节数组转换为一个单字节在这一行:

I assume that imageBytes is an array of bytes (byte[]). As your code compiles, the Photo property must be of type byte. You try to convert the byte array to a single byte in this line:

objUser.Photo = Convert.ToByte( imagebytes);  

这导致了一个例外,因为字节数组不执行 IConvertible 这将在订货时所需的转换工作。但是,你会如何想的字节数组转换为一个字节呢?转换机构应如何知道分配给单个字节其中所述阵列的字节?因此,我怀疑你宁愿希望照片属性也是类型字节[] ,以便它能够存储完整的画面,而不是只有一个的它的字节。

This leads to an exception as the byte array does not implement IConvertible which would be required in order for the conversion to work. But how would you want to convert a byte array to a single byte anyway? How should the conversion mechanism know which byte of the array to assign to the single byte? Therefore I suspect that you'd rather want the Photo property to also be of type byte[] so that it is able to store the complete picture and not only one byte of it.

因此​​,为了解决这个问题,尽量在实体的属性更改为字节[] (这也可能涉及到更改数据库架构)和数组直接分配不使用 Convert.ToByte()

So in order to fix this, try to change the property in your Entity to byte[] (which might also involve changing the database schema) and assign the array directly without using Convert.ToByte().

这篇关于"无法投类型的对象'System.Byte []'键入'System.IConvertible'&QUOT。错误照片:为什么和如何解决呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆