1

这个类正在抛出异常。它没有向我显示确切的行号,但听起来它发生在静态构造函数中:

static class _selectors
{
    public static string[] order = new[] { "ID", "NAME", "TAG" };
    public static Dictionary<string, Regex> match = new Dictionary<string, Regex> {
        { "ID", new Regex(@"#((?:[\w\u00c0-\uFFFF-]|\\.)+)") },
        { "CLASS", new Regex(@"\.((?:[\w\u00c0-\uFFFF-]|\\.)+)") },
        { "NAME", new Regex(@"\[name=['""]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['""]*\]") },
        { "ATTR", new Regex(@"\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['""]*)(.*?)\3|)\s*\]") },
        { "TAG", new Regex(@"^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)") },
        { "CHILD", new Regex(@":(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?") },
        { "POS", new Regex(@":(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)") },
        { "PSEUDO", new Regex(@":((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['""]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?") }
    };
    public static Dictionary<string, Action<HashSet<XmlNode>, string>> relative = new Dictionary<string, Action<HashSet<XmlNode>, string>> {
        { "+", (checkSet, part) => {
        }}
    };
    public static Dictionary<string, Regex> leftMatch = new Dictionary<string, Regex>();
    public static Regex origPOS = match["POS"];

    static _selectors()
    {
        foreach (var type in match.Keys)
        {
            _selectors.match[type] = new Regex(match[type].ToString() + @"(?![^\[]*\])(?![^\(]*\))");
            _selectors.leftMatch[type] = new Regex(@"(^(?:.|\r|\n)*?)" + Regex.Replace(match[type].ToString(), @"\\(\d+)", (m) =>
                @"\" + (m.Index + 1)));
        }
    }
}

为什么我不能更改 c'tor 中的这些值?

4

3 回答 3

2

如果您查看内部异常,您将看到它声明

收藏已修改;枚举操作可能无法执行。

这意味着您正在更改正在循环的集合,这是不允许的。

而是将您的构造函数更改为类似

static _selectors()
{
    List<string> keys = match.Keys.ToList();
    for (int iKey = 0; iKey < keys.Count; iKey++)
    {
        var type = keys[iKey];
        _selectors.match[type] = new Regex(match[type].ToString() + @"(?![^\[]*\])(?![^\(]*\))");
        _selectors.leftMatch[type] = new Regex(@"(^(?:.|\r|\n)*?)" + Regex.Replace(match[type].ToString(), @"\\(\d+)", (m) =>
            @"\" + (m.Index + 1)));
    }
}
于 2010-09-23T11:47:24.390 回答
1

简单的诊断方法:将所有代码移到普通方法中,并找出以这种方式抛出的异常。或者只是在调试器中运行它——抛出异常时应该会中断。

我怀疑这将是一个糟糕的正则表达式或类似的东西。

就个人而言,我认为这在静态构造函数中逻辑太多,但这是一个稍微不同的问题......请注意,您还依赖于这里的初始化顺序:

public static Regex origPOS = match["POS"];

目前保证没问题,但它非常脆弱。

于 2010-09-23T11:45:04.317 回答
1

您在枚举集合时正在修改它。你不能那样做。快速修复是将键移动到不同的集合中并枚举:

static _selectors()
{
    foreach (var type in match.Keys.ToArray())
    {

此外,如果您检查了内部异常,您会发现情况确实如此。

于 2010-09-23T11:48:11.440 回答