ªð¦^¦Cªí ¤W¤@¥DÃD µo©«

[¤À¨É] C# ª«¥ó§Ç¦C¤Æ»P¤Ï§Ç¦C¤Æ

[¤À¨É] C# ª«¥ó§Ç¦C¤Æ»P¤Ï§Ç¦C¤Æ

C#ªºª«¥ó§Ç¦C¤Æ¥i±N°õ¦æ®É´Áªºª«¥óª¬ºA¿é¥X¦Üstream¡C¥»¤å¤¶²Ð¨Ï¥ÎBinaryFormatterªº¤èªk¡C
¨Ï¥ÎBinaryFormatter»Ý¤Þ¥Î¤U¦C©R¦WªÅ¶¡¡G
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

­n«O¦sª¬ºAªºÃþ§O©w¸q»Ý­n¼Ð°O[Serializable]ÄÝ©Ê¡A¨Ò¦p¤@­Ó²³æªºÃþ§O«Å§i¦p¤U¡G
    [Serializable]
    class MyContact
    {
        public string name;
        public int age;
        
        public MyContact(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
    }

±N°õ¦æ­ÓÅ骺ª¬ºA«O¦s¦¨ÀɮסG
    MyContact data = new MyContact("John", 14);
    IFormatter fmt = new BinaryFormatter();
    Stream ostream = new FileStream("MyData.binary", FileMode.Create, FileAccess.Write, FileShare.None);
    fmt.Serialize(ostream, data);
    ostream.Close();
³oÃä¨Ï¥Î¤FFileStream(¤Þ¥ÎSystem.IO)¡C
¤èªk¦P¼Ë¾A¥Î©óStreamªº­l¥ÍÃþ§O¡C

¨Ï¥Î¦P¼ËªºÃþ§O«Å§i¡A±qÀɮפϧǦC¤Æ¡G

    Stream istream = new FileStream("MyData.binary", FileMode.Open,
        FileAccess.Read, FileShare.Read);
    MyContact data = (MyContact)fmt.Deserialize(istream);
    istream.Close();
   
    // data.name = ??

TOP

¥t¤@ºØ¤èªk¬O±Nª«¥ó§Ç¦C¤Æ¦¨XMLªº®æ¦¡¡A¨Ï¥ÎXmlSerializer¡C(¤Þ¥ÎSystem.Xml.Serialization©R¦WªÅ¶¡)

    MyContact data = new MyContact("John", 14);
    XmlSerializer fmt = new XmlSerializer(typeof(MyContact));
    Stream ostream = new FileStream("MyData.xml", FileMode.Create, FileAccess.Write, FileShare.None);
    fmt.Serialize(ostream, data);
    ostream.Close();

»PBinaryFormatter¤ñ¸û¤@¤U¡A®t§O¥u¦b¥Î¨Ó§Ç¦C¤ÆªºÃþ§O¤£¦P¡C
¥Î³oºØ¤èªk­nª`·N¦s¨ú­×¹¢¤l¤Î´£¨Ñ¹w³]«Øºc¤l¡C³o­Ó¨Ò¤l·|²£¥Í³o¼Ëªº¿é¥Xµ²ªG¡G
<?xml version="1.0"?>
<MyContact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>John</name>
  <age>14</age>
</MyContact>

TOP

        ÀR«ä¦Û¦b : ¡i¬O§_µo´§¤F¨}¯à¡H¡j¤H¶¡¹Ø©R¦]¬°µu¼È¡A¤~§óÅã±o¬Ã¶Q¡CÃø±o¨Ó¤@½ë¤H¶¡¡AÀ³°Ý¬O§_¬°¤H¶¡µo´§¤F¦Û¤vªº¨}¯à¡A¦Ó¤£­n¤@¨ý¨Dªø¹Ø¡C
ªð¦^¦Cªí ¤W¤@¥DÃD