在您的示例中,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
函数,很可能会破坏。