close
前幾篇文章討論到 Expression Evaluation,無奈這些都不太合用,後來不小心看到了 SPRING.net,才發現原來有這麼強大的 Framework。
SPRING.net 的功能很多,這邊僅討論 spring.core 底下的 Expression Evaluation。使用方式很簡單且直覺,直接呼叫 ExpressionEvaluator.GetValue 就可以了。例如:
ExpressionEvaluator.GetValue(null, "3")
它會回傳一個 object,而型態則是整數。如果要取物件底下的 property,例如要得知字串大小,則可以這樣寫:
string str = "this is test string."; object obj = ExpressionEvaluator.GetValue(str, "Length");
最後回傳的 obj 就是一個整數值。
除此之外,還能直接存取 indexer,像是一般的陣列:
int[] intArray = { 0, 1, 2 }; object obj = ExpressionEvaluator.GetValue(intArray, "[1]");
也支援 Dictionary 這類的物件:
Dictionary<string, int> dic = new Dictionary<string, int>(); dic.Add("a", 0); dic.Add("b", 1); object obj = ExpressionEvaluator.GetValue(dic, "['b']");
如果想設定多個變數,可以用以下的寫法:
Dictionary<string, object> vars = new Dictionary<string, object>(); vars.Add("a", 3); vars.Add("b", 4); vars.Add("c", new TestClass { Field3 = 9, Field4 = new int[] { 1, 2, 3 }, Filed5 = new TestClass { Field3 = 5 } }); object obj = ExpressionEvaluator.GetValue(null, "#a+#b+#c.Field4[0]", vars); obj.PrintValueAndTypeName();
參考資料
http://www.springframework.net/doc-latest/reference/html/expressions.html
全站熱搜