您的位置:首页 > 编程语言 > C#

C# byte[]数组,问答

2013-03-07 20:42 232 查看

 

 

 
问:

比如   byte[]   cmdData   =   {85,85,83,83,255,123,99,33,55,1,1}

长度为   11

用什么方法可以   从   第4位开始截取   5   个

即:255,123,99,33,55

答:

byte[]   cmdData   =   {   85,   85,   83,   83,   255,   123,   99,   33,   55,   1,   1   };

                        byte[]   newData   =   new   byte[5];

                        Array.Copy(cmdData,   4,   newData,0,   5);

--------------------------------------------------------------------------------------

问:

比如有:

  byte[]   a   =   {0x01,0x02,0x03};

  byte[]   b   =   {0x04,0x05,0x06};

  byte[]   c;

有没有比较简单的方法来连接a   和   b   两个数组到c里去?而不用循环来写进去?

答:

byte[]   c   =   new   byte[a.Length   +   b.Length];

a.CopyTo(c,   0);

b.CopyTo(c,   a.Length);

 

--------------------------------------------------------------------------------------

问:

怎样把Object对象转换成字节数组?

请问怎样把Object对象转换成字节数组,用来在网络上传输?非常感谢!!!!

答:

----------------------

问如何将对象的实体转换为byte[]?

    [Serializable]

        public class student

        {

            public string name;

            public int age;

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            student student1 = new student();

            student1.name = "zhangsan";

            student1.age = 10;

            byte[] tBytes = null;

            using (MemoryStream memoryStream = new MemoryStream())

            {

                BinaryFormatter binaryFormatter = new BinaryFormatter();

                binaryFormatter.Serialize(memoryStream, student1);

                tBytes = memoryStream.ToArray();

            }

-------------------------

2序列化和反序列化

  首先这个类必须是可序列化的,例如DataTable,又或者下面这样:

[Serializable]

public class GradResume

{

/// <summary>

/// 用户ID。

/// </summary>

public string UserID;

/// <summary>

/// 登录名。

/// </summary>

public string UserName;

.......................

序列化和反序列化的代码如下:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters;

using System.Runtime.Serialization.Formatters.Binary;

||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

//新建类GradResume的实例

GradResume aaa = new GradResume();

aaa.UserID = "123";

aaa.UserName = "eddiezhong";

//序列化对象

BinaryFormatter binaryFormatter = new BinaryFormatter();

System.IO.MemoryStream mStm1 = new System.IO.MemoryStream();

binaryFormatter.Serialize(mStm1,aaa);

byte[] tmpBytes = mStm1.ToArray();

mStm1.Close();

//tmpBytes就可以用来保存数据库了或者写文件

//读数据库或者文件文件重新获得tmpBytes

//反序列化二进制数组

System.IO.MemoryStream mStm2 = new System.IO.MemoryStream(tmpBytes);

mStm2.Position = 0;

object newObj = binaryFormatter.Deserialize(mStm2);

mStm2.Close();

//得到GradResume对象

GradResume bbb = (GradResume)newObj;

this.TextBox1.Text = bbb.UserID;

this.TextBox2.Text = bbb.UserName;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: