我想序列化我的具有属性IPAddress的类.
public class Person { public IPAddress MasterIP { get; set; } public Person(){} } public void SerializeMyClass() { Person obj=new Person(); XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType()); xmlSerializer.Serialize(obj); }
但是我收到了错误:
“can not serialize IPaddress because it has no empty constructor”
解决方法
您不能 – XmlSerializer只能序列化具有公共无参数构造函数的公共类的公共属性/字段.您可以查看其他序列化程序类型(如BinaryFormatter)或破解您的类,如:
public class Person { [XmlIgnore] public IPAddress MasterIP { get; set; } [XmlElement("MasterIP")] public string MasterIPForXml { get { return MasterIP.ToString(); } set { MasterIP = string.IsNullOrEmpty(value) ? null : IPAddress.Parse(value); } } }