Запись опубликована 32 bit.me. You can comment here or there.
При попытке сериализации объекта с полем вида
public IPAddress ip
возникает Run-time error типа System.InvalidOperationException
Причина заключается в том, что класс IPAddress не имеет конструктора по умолчанию (parameterless ctor), необходимый для XML-сериализации, при этом то, что класс IPAddress имеет атрибут [SerializableAttribute], не имеет значения, т.к. этот атрибут действует только на binary и Soap-сериализацию.
Решается проблема, например, так:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Xml.Serialization; using System.IO; namespace SerializationTest { public enum MyEnum { enum1, enum2, enum3 } [Serializable] public class Test { public Test() { a = 1; b = true; s = "string"; ip = IPAddress.Loopback; } public int a; public bool b; public string s; public MyEnum e; [XmlElement(ElementName = "IPAddress")] public string IPAddressAsString { get { return ip != null ? ip.ToString() : null; } set { IPAddress a; if (value != null && IPAddress.TryParse(value, out a)) ip = a; else ip = null; } } [XmlIgnore] public IPAddress ip { get; set; } } class Program { static void Main(string[] args) { Test test = new Test(); XmlSerializer xs = new XmlSerializer(typeof(Test)); FileStream writer = new FileStream("file.xml", FileMode.OpenOrCreate); xs.Serialize(writer, test); writer.Close(); } } } |