代码之家  ›  专栏  ›  技术社区  ›  mpen

类型初始值设定项引发异常

  •  1
  • mpen  · 技术社区  · 15 年前

    此类正在引发异常。它没有显示确切的行号,但听起来像是在静态构造函数中发生的:

    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中更改这些值?

    3 回复  |  直到 15 年前
        1
  •  1
  •   user1228 user1228    15 年前

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

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

    另外,如果您检查了内部异常,您就会看到情况是这样的。

        2
  •  2
  •   Adriaan Stander    15 年前

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

    操作可能无法执行。

    不如把构造器改成

    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)));
        }
    }
    
        3
  •  1
  •   Jon Skeet    15 年前

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

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

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

    那个 现在肯定没事,但很脆弱。