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

标签 c# c#-3.0

如何转义索引器中的点?第一个 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/

相关文章:

c# - 我如何从不同的线程获取 bool 值?

c# - 从命令行运行时,NUnit 看不到 configSource 定义的连接字符串

c# - 确定类型是否为匿名类型

c# - 有没有办法强制转换函数

c# - 在 Entity Framework C# 中返回列表的最大列表

c# - ContentDisposition 类抛出不一致的异常

c# - 新站点创建和安全/身份验证——我应该使用 ASP.net Membership Provider 吗?

c# - 用 3 位数字分隔长号

c#-3.0 - C#中 'var'的邪恶之处?

c# - 将整数转换为罗马数字