简体   繁体   English

如何使用 .NET XML 序列化正则表达式类型

[英]How to serialize a regular expression type using .NET XML serialization

How can I serialize a string from XML into a class property of type Regex ?如何将 XML 中的字符串序列化为Regex类型的 class 属性?

Here's the elements in the XML file:这是 XML 文件中的元素:

  <IncludeRegex><![CDATA[#include\\s*\\\"\\s*(?<FileName>.+\\\\*\\.*.+)\\s*\\\"]]></IncludeRegex>
  <IncludeDefineRegex><![CDATA[#define\s*[A-Za-z_0-9]+\s*\""\s*(?<FileName>.+\.[a-zA-Z0-9]+)\s*\""]]></IncludeDefineRegex>

In my class, that I serialize, I have these properties:在我序列化的 class 中,我具有以下属性:

public Regex IncludeRegex { get; set; }
public Regex IncludeDefineRegex { get; set; }

The rest of the class serializes without a problem, but the Regex properties fail to serialize. class 的 rest 序列化没有问题,但Regex属性序列化失败。 One option is to have alternate properties:一种选择是具有备用属性:

public string IncludeRegex { get; set; }
public string IncludeDefineRegex { get; set; }
[XmlIgnore]
public Regex IncludeRegexActual { get; private set; }

[XmlIgnore]
public Regex IncludeDefineRegexActual { get; private set; }

And set these properties in the setters of IncludeRegex and IncludeDefineRegex or an init function.并在 IncludeRegex 和 IncludeDefineRegex 或 init function 的设置器中设置这些属性。 This works, but can I do it without the duplicate properties?这行得通,但是我可以在没有重复属性的情况下做到这一点吗?

I don't think you can do that with regular XML serialization, you have to implement IXmlSerializable to control the serialization directly.我认为你不能用常规的 XML 序列化来做到这一点,你必须实现IXmlSerializable来直接控制序列化。

The problem is, that Regex cannot be serialized.问题是,Regex 不能被序列化。 That can be solved by implementing IXmlSerializable .这可以通过实现IXmlSerializable来解决。 As you cannot change the Regex class, you have to handle it in another class.由于您无法更改正则Regex class,因此您必须在另一个 class 中处理它。 You might be able to do something like this (untested, out of my head):你也许可以做这样的事情(未经测试,在我脑海中):

public class MyRegEx : Regex, IXmlSerializable {...}

Now you have to implement the interface and have to use that class instead of Regex.现在您必须实现接口并且必须使用 class 而不是正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM