我用下面的代码可以将对象转换为byte[],可是对象数组怎么转换呢?        Class2 c=new Class2();
        c.A="faf";
        c.B="ffff";
        c.C="测试";
        BinaryFormatter bf=new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, c);
        byte[] bb = ms.GetBuffer();比如:Class2[] c=new Class[2];
那么这个c怎么转换成byte[]呢?用上面的方法不行?
对这点不太熟悉.谢谢!

解决方案 »

  1.   

    是一样的
    [Serializable] 
      class Class2
      {
        public string A;
        public string B;
        public string C;
      } BinaryFormatter bf = new BinaryFormatter();
          MemoryStream ms = new MemoryStream();
          Class2[] cc = new Class2[2];
          cc[0] = new Class2();
          cc[0].A = "how";
          cc[1] = new Class2();
          cc[1].B = "are you";
          bf.Serialize(ms, cc);
          byte[] bb = ms.GetBuffer();      ms = new MemoryStream(bb);
          cc=(Class2[])bf.Deserialize(ms);
      

  2.   

    Encoding.utf8.getbytes(string c);绝对正确;
      

  3.   

    用序列化就能把对象转换为byte[]
      

  4.   

    序列化对象的方法: public static byte[] Serialize(object aObject) 
            { 
                //序列化发送内容 
                MemoryStream aMemoryStream = new MemoryStream(); 
                BinaryFormatter aBinaryFormatter = new BinaryFormatter(); 
                aBinaryFormatter.Serialize(aMemoryStream, aObject); 
                 
                return aMemoryStream.ToArray(); 
            } 
      

  5.   

    对象必需加[Serializable] 属性才能被序列化,必要的时候,必要时需继承一下ISerializable并实现其接口成员方法来实现对象的序列化,从而使用Byte数组来表示对象。
      

  6.   

    例如:[Serializable]
    public class MyObject : ISerializable 
    {
      public int n1;
      public int n2;
      public String str;  public MyObject()
      {
      }  protected MyObject(SerializationInfo info, StreamingContext context)
      {
        n1 = info.GetInt32("i");
        n2 = info.GetInt32("j");
        str = info.GetString("k");
      }
      public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
      {
        info.AddValue("i", n1);
        info.AddValue("j", n2);
        info.AddValue("k", str);
      }
    }
      

  7.   

    先toString,然后用System.Text.Encoding.UTF8.GetByte