netnr 2022-07-19

引言

构建实体对象,序列化为 XML 文件存储,使用时反序列化 XML 为实体对象(含有正则 Regex 对象),在测试、发布都正常,但勾选 裁剪未使用的代码 后反序列化 XML 就报错了

System.Text.RegularExpressions.Regex cannot be serialized because it does not have a parameterless constructor

解决办法

添加 [XmlIgnore] 标记,忽略该对象

public class OSEntity
{
    /// <summary>
    /// 正则
    /// </summary>
    [XmlIgnore]
    public Regex R { get; set; }
    /// <summary>
    /// 正则
    /// </summary>
    public string Regex { get; set; }
    /// <summary>
    /// 名称
    /// </summary>
    public string Name { get; set; }
}

附上 XML 的(反)序列化方法

/// <summary>
/// 生成 XML (序列化)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToXml(object obj)
{
    if (obj == null) return null;

    using var sw = new StringWriter();
    var serializer = new XmlSerializer(obj.GetType());
    serializer.Serialize(sw, obj);
    return sw.ToString();
}
/// <summary>
/// XML 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T ToEntity<T>(string xml)
{
    if (string.IsNullOrWhiteSpace(xml)) return default;

    using var sr = new StringReader(xml);
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(sr);
}
登录写评论