【问题标题】:Jint: using CLR object 's properties in Javascript functionsJint:在 Javascript 函数中使用 CLR 对象的属性
【发布时间】:2020-09-17 14:06:30
【问题描述】:

我一直在测试 jint 库并遇到了问题。鉴于 C# 中的此类:

public class Foo
{
    public string Name { get; } = "Bar";
}

还有这段代码:

Engine engine = new Engine(x => x.AllowClr());

object rc = _engine
    .SetValue("foo", new Foo())
    .Execute("foo.Name.startsWith('B')")
    .GetCompletionValue()
    .ToObject();

我收到错误:'Jint.Runtime.JavaScriptException: 'Object has no method 'startsWith'''

但是,这可行:

"foo.Name == 'Bar'"

那么我可以让前者工作吗?

【问题讨论】:

  • 应该是大写吗? .StartsWith
  • StartsWith (.NET) 和 startsWith (JS) 都不起作用

标签: javascript .net jint


【解决方案1】:

增加了对扩展方法的支持here。但不能让它直接与 .NET 字符串扩展方法一起使用,它确实与中间扩展类一起使用。

更新:像StartsWith 这样的字符串方法确实不是真正的扩展方法。

看起来现在已经原生支持startsWith。将GetCompletionValue 替换为建议的Evaluate

// Works natively with Jint 3.0.0-beta-2032
Engine engine = new Engine();

bool result = engine
    .SetValue("foo", new Foo())
    .Evaluate("foo.Name.startsWith('B')")
    .AsBoolean();

我尝试添加 string 扩展方法,但这似乎不起作用。但是使用您自己的类作为扩展方法并以这种方式使用它确实有效。

public static class CustomStringExtensions
{
    public static bool StartsWith(this string value, string value2) =>
      value.StartsWith(value2);
}

Engine engine = new Engine(options =>
{
    options.AddExtensionMethods(typeof(CustomStringExtensions));
});

bool result = engine
    .SetValue("foo", new Foo())
    .Evaluate("foo.Name.StartsWith('B')")
    .AsBoolean();

我询问过原生扩展方法是否支持 here,因为我很好奇它是否以及应该如何工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2013-10-11
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多