如何将字节数组转换为任何类型 [英] How to convert byte array to any type

查看:188
本文介绍了如何将字节数组转换为任何类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我看到有人问如何将字节数组转换为intstringStream等...,这些问题的答案各不相同,我个人没有发现任何问题.满意的答案.

okay guys I'm seeing question from persons asking how to convert byte arrays to int, string, Stream, etc... and the answers to which are all varying and I have personally not found any satisfactory answers.

因此,这是一些我们要将字节数组转换为的类型.

So here are some types that we want to convert an array of bytes to.

UnityEngine.Font可以接收ttf数据.

UnityEngine.Testure2D,h可以从图像文件中获取数据,例如.png.jpg等...

UnityEngine.Testure2D which h can take in data from image files like .png, .jpg, etc...

我们如何将字节数组转换为StringUnityEngine.Testure2D,UnityEngine.FontBitmap等...

How would we convert a byte array to a String, UnityEngine.Testure2D,UnityEngine.Font, Bitmap, etc...

填充字节数组的数据必须来自文件类型,该文件类型的数据可以由我们要将字节数组转换为的类型来管理?

The data that populates the byte array must be from a file type whose data can by managed by the type we want to convert the byte array to?

这当前可行吗?

任何帮助将不胜感激.

推荐答案

原始类型很容易,因为它们具有定义为字节数组的表示形式.其他对象不是因为它们可能包含无法持久保存的内容,例如文件句柄,对其他对象的引用等.

Primitive types are easy because they have a defined representation as a byte array. Other objects are not because they may contain things that cannot be persisted, like file handles, references to other objects, etc.

您可以使用

You can try persisting an object to a byte array using BinaryFormatter:

public byte[] ToByteArray<T>(T obj)
{
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    using(MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

public T FromByteArray<T>(byte[] data)
{
    if(data == null)
         return default(T);
    BinaryFormatter bf = new BinaryFormatter();
    using(MemoryStream ms = new MemoryStream(data))
    {
        object obj = bf.Deserialize(ms);
        return (T)obj;
    }
}

但并非所有类型都可以序列化.例如,没有办法存储"到数据库的连接.您可以存储用于创建连接的信息(如连接字符串),但不能存储实际的连接对象.

But not all types are serializable. There's no way to "store" a connection to a database, for example. You can store the information that's used to create the connection (like the connection string) but you can't store the actual connection object.

这篇关于如何将字节数组转换为任何类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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