数据对象操作 [英] Data Object Manipulation

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

问题描述

您好,例如,我有一个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 :)

推荐答案

事情并非如此简单:它取决于您的课程内容.如果它具有对其他类的引用(可能如此),则还需要包括这些类.
将其转换为原始字节数组非常简单:
It''s not as simple as that: it depends on what you class contains. If it has references to other classes (as it probably does) then you need to include those as well.
To convert it to a raw byte array is pretty simple:
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();
        }
    }


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

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