0

当我使用以下代码段时,我得到一个 ScrptEngineException,该对象不支持该属性或方法。

var engine = new JScriptEngine();
engine.AddHostType("String", typeof(System.String));
engine.ExecuteCommand("test = 'variabel'; test.StartsWith('nice');");

我尝试了其他一些字符串函数,如 IndexOf、ToArray (Extension) 和其他一些,但似乎不起作用。

有人可以帮我吗?

4

1 回答 1

1

在您的示例中,test是一个 JavaScript 字符串,它没有StartsWith方法。即使它是从 .NET 返回的,为了方便起见,它也会被转换为 JavaScript 字符串。

您可以添加一个将 JavaScript 字符串转换为 .NET 字符串的方法:

engine.AddHostObject("host", new HostFunctions());
engine.Execute(@"
    String.prototype.toHost = function() {
        return host.newVar(this.valueOf());
    }
");

然后这应该工作:

engine.AddHostType(typeof(Console));
engine.Execute(@"
    test = 'variable';
    Console.WriteLine(test.toHost().StartsWith('var'));
    Console.WriteLine(test.toHost().StartsWith('vaz'));
");

顺便说一句,请注意这一点:

engine.AddHostType("String", typeof(System.String));

这隐藏了内置的 JavaScriptString函数,很可能会破坏。

于 2018-07-04T18:23:53.423 回答