Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c# - How to convert byte array to any type

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 which can take in ttf data.

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

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?

Is this currently possible?

Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...