是否可以使用“;javascript点表示法”;在JINT with a Dictionary<字符串,对象>

Is it possible to use "javascript dot notation" in JINT with a Dictionary<string, object>

本文关键字:Dictionary with lt 字符串 gt 对象 JINT 可以使 javascript 表示 是否      更新时间:2023-09-26

我有一组JavaScript命令,如doc.page == 5,我正在使用JINT在我的C#应用程序中执行这些脚本。

然而,在我的C#代码中,docDictionary<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);
    }
}