当我使用以下代码段时,出现ScrptEngineException异常,表明该对象不支持属性或方法。
var engine = new JScriptEngine();
engine.AddHostType("String", typeof(System.String));
engine.ExecuteCommand("test = 'variabel'; test.StartsWith('nice');");
我尝试了其他一些StringFunction,如IndexOf,ToArray(扩展)和其他一些,但似乎不起作用。
有人可以帮我吗?
答案 0 :(得分: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));
这隐藏了内置的JavaScript String
函数,很可能会破坏事情。