如何转义索引器中的点?第一个 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.
最佳答案
DataBinder.Eval 首先通过一组 char 标记(它在静态构造函数中定义为)按表达式部分拆分字符串:
expressionPartSeparator = new char[] { '.' };
然后它将这些部分传递到私有(private) Eval 方法中,该方法将根据需要使用 DataBinder.GetPropertyValue 或 DataBinder.GetIndexedPropertyValue 来进一步确定表达式的值。
要绕过这个,只需像这样直接对字符串表达式使用 GetIndexedPropertyValue:
Console.WriteLine(DataBinder.GetIndexedPropertyValue(blah, "dict[a.aa]" ));
另请注意,您不需要额外的引号……它们太过分了。
关于c# - 将 DataBinder.Eval 与包含句点的索引器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/459168/