文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>.NET对象序列化—IPAddress

.NET对象序列化—IPAddress

时间:2011-05-05  来源:Asharp

       IPAddress没有默认的构造函数,不能正常序列化。IPAddrss支持的构造函数有:

   1: public IPAddress(byte[] address);
   2: public IPAddress(long newAddress);
   3: public IPAddress(byte[] address, long scopeid);

      示例代码:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         TestClass testClass = new TestClass();
   6:         
   7:         using (MemoryStream stream = new MemoryStream())
   8:         {
   9:             XmlSerializer ser = new XmlSerializer(typeof(TestClass));
  10:             ser.Serialize(stream, testClass);
  11:             string result = Encoding.UTF8.GetString(stream.ToArray());
  12:         }
  13:     }
  14: }
  15:  
  16: public class TestClass
  17: {
  18:     public IPAddress IP { get; set; }
  19: }

     运行时提示:

       解决方案,扩展IPAddress:

   1: class Program
   2: {
   3:     static void Main(string[] args)
   4:     {
   5:         TestClass testClass = new TestClass();
   6:         testClass.IP.IPAddressAsString = "127.0.0.1";
   7:         
   8:         using (MemoryStream stream = new MemoryStream())
   9:         {
  10:             XmlSerializer ser = new XmlSerializer(typeof(TestClass));
  11:             ser.Serialize(stream, testClass);
  12:             string result = Encoding.UTF8.GetString(stream.ToArray());
  13:         }
  14:     }
  15: }
  16:  
  17: public class TestClass
  18: {
  19:     public IPAddressEx IP { get; set; }
  20:  
  21:     public TestClass()
  22:     {
  23:         this.IP = new IPAddressEx();
  24:     }
  25: }
  26:  
  27: public class IPAddressEx
  28: {
  29:     [XmlElement(ElementName = "IPAddress")]
  30:     public string IPAddressAsString
  31:     {
  32:         get { return IPAddress != null ? IPAddress.ToString() : null; }
  33:         set
  34:         {
  35:             IPAddress ip;
  36:             if (value != null && IPAddress.TryParse(value, out ip))
  37:                 IPAddress = ip;
  38:             else
  39:                 IPAddress =null;
  40:         }
  41:     }
  42:     [XmlIgnore]
  43:     public IPAddress IPAddress { get; set; }
  44: }

       序列化结果:

  
   1: <?xml version="1.0"?>
   2: <TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   3:   <IP>
   4:     <IPAddress>127.0.0.1</IPAddress>
   5:   </IP>
   6: </TestClass>
   6: </TestClass>
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载