本文介绍了数据对象操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,例如,我有一个Client类:

hello, as example i have a class Client :

Class Client
   {
        public Client(string name)
          {
            Name = name;
          }
        private string Name
          {
            get;
            set;
          }
    }
/*This is not my class case, i might have any other class, i need a general solution not depending on class internal structures and fields */


因此,我使用了:


so, i used:

Client CLI = new Client("John");


我需要将数据对象CLI转换为等效的byte []表示形式
我该怎么办?
感谢您的帮助:)


i need to convert my data object CLI to a byte[] equivalent representation
how can i ?
thank''s for any help :)

推荐答案

private static byte[] ToByteArraySimple(object o)
    {
    int length = Marshal.SizeOf(o);
    byte[] bytes = new byte[length];
    IntPtr start = Marshal.AllocHGlobal(length);
    Marshal.StructureToPtr(o, start, false);
    Marshal.Copy(start, bytes, 0, length);
    Marshal.FreeHGlobal(start);
    return bytes;
    }


但是为了安全起见,请使用Serializable属性(以及所有引用的类)标记您的类,然后使用Binary Formatter:


But to be safe, mark your class with the Serializable attribute (and all referenced classes) and use a Binary Formatter:

private static byte[] ToByteArrayBetter(object o)
    {
    var formatter = new BinaryFormatter();
    using (var stream = new MemoryStream())
        {
        formatter.Serialize(stream, o);
        return stream.ToArray();
        }
    }


这篇关于数据对象操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:12