是否可以使用“;javascript点表示法”;在JINT with a Dictionary<字符串,对象>
Is it possible to use "javascript dot notation" in JINT with a Dictionary<string, object>
我有一组JavaScript命令,如doc.page == 5
,我正在使用JINT在我的C#应用程序中执行这些脚本。
然而,在我的C#代码中,doc
是Dictionary<string, object>
。因此,我不能以这种方式使用点表示法。
我目前的解决方案效率非常低:我将doc
转换为JSON字符串,并将其添加到我的脚本中。Dictionary
非常大,因此这比执行简单的命令有更多的开销。下面是一些示例代码:
// Some example data:
var command = "doc.page < 5 || doc.tax < 10 || doc.efile";
var doc = new Dictionary<string, object>(){
{"page", 5},
{"tax", 10},
{"efile", true},
// ... etc ...
};
// Execute the command:
// Convert Dictionary to JSON:
var jsonDoc = new StringBuilder();
jsonDoc.Append("var doc = {");
var first = true;
foreach (var kv in doc) {
if (!first) {
jsonDoc.Append(",");
}
first = false;
jsonDoc.AppendFormat("{0}: {1}", kv.Key, kv.Value);
}
jsonDoc.Append("};");
var je = new JintEngine();
je.Run(jsonDoc.ToString());
var result = je.Run(command);
return result;
有什么方法可以更有效地做到这一点吗?
也许您可以利用dynamic
将点表示法语法引入字典。我还没有用JINT测试,但我认为它会起作用。
下面是一个基于DynamicObject
包装Dictionary的示例(忽略了一些类型安全性,但您得到了大致的想法:-)。您应该能够将其调整为与JINT一起工作。
void Main()
{
var values = new Dictionary<string,object> {
{ "x", 5 }, { "Foo", "Bar" }
};
dynamic expando = new ExpandoDictionary(values);
// We can lookup members in the dictionary by using dot notation on the dynamic expando
Console.WriteLine(expando.x);
// And assign new "members"
expando.y = 42;
expando.Bar = DateTime.Now;
// The value set is in the dictionary
Console.WriteLine(values["Bar"]);
}
public class ExpandoDictionary : DynamicObject
{
private readonly Dictionary<string,object> inner;
public ExpandoDictionary(Dictionary<string,object> inner)
{
this.inner = inner;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
inner[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object value)
{
return inner.TryGetValue(binder.Name, out value);
}
}
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 指令的模板必须只有一个根元素:With restrict E&替换true
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- Architecture for CPU intensive tasks with NodeJS & Socke
- How to declare a Map containing certain properties with flow
- 设置'这'在React with Inverse Data Flow中
- Unit-testing multiple use cases with Karma & Mocha.js
- Javascript中Dictionary的访问列表
- Modify Javascript with C#
- 谷歌地图API v3:Initial View is Fine,but Gray Box with No Map if
- 是否可以使用“;javascript点表示法”;在JINT with a Dictionary<字符串,对象>