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

将DataBinder.Eval与包含句点的索引器一起使用

  •  3
  • chilltemp  · 技术社区  · 16 年前

    如何避开索引器中的点?第一个DataBinder.Eval按预期工作。第二个抛出一个异常。

    System.ArgumentException: DataBinding: 'dict["a' is not a valid indexed expression.
    
    
    Dictionary<string, int> dict = new Dictionary<string, int>();
    dict.Add("aaa", 111);
    dict.Add("bbb", 222);
    dict.Add("ccc", 333);
    dict.Add("ddd", 444);
    dict.Add("a.aa", 555);
    var blah = new { dict = dict, date = DateTime.Now };
    
    Console.WriteLine(DataBinder.Eval(blah, "dict[\"aaa\"]")); 
    // 111
    
    Console.WriteLine(DataBinder.Eval(blah, "dict[\"a.aa\"]")); 
    // System.ArgumentException: DataBinding: 'dict["a' is not a valid indexed expression.
    
    2 回复  |  直到 16 年前
        1
  •  3
  •   Lusid    16 年前

    Eval首先通过一组字符标记(它在静态构造函数中定义为)将字符串按表达式部分拆分:

    expressionPartSeparator = new char[] { '.' };
    

    然后,它将这些部分传递到私有Eval方法中,该方法将根据需要使用DataBinder.GetPropertyValue或DataBinder.GetIndexedPropertyValue来进一步确定表达式的值。

    Console.WriteLine(DataBinder.GetIndexedPropertyValue(blah, "dict[a.aa]" ));
    

    还请注意,您不需要额外的报价。。。他们太过分了。

        2
  •  1
  •   BFree    16 年前

    请改用此方法:

    Console.WriteLine(DataBinder.GetIndexedPropertyValue(blah, "dict[\"a.aa\"]"));