2009-01-19 47 views
3

如何在索引器中轉義點?第一個DataBinder.Eval按預期工作。第二個拋出異常。對包含句點的索引器使用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. 

回答

3

的DataBinder.Eval第一經由炭令牌的一組陣列(它在靜態構造爲限定)分割的字符串增長表達部分:

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

然後它將這些部分傳遞給私有的Eval方法,該方法將根據需要使用DataBinder.GetPropertyValue或DataBinder.GetIndexedPropertyValue來進一步確定表達式的值ñ。

要繞過這一點,只需直接使用GetIndexedPropertyValue與字符串表達式如下所示:

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

另外請注意,你不需要額外的報價...他們是矯枉過正。

1

使用此方法來代替:

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