【问题标题】:ScriptengineException when string methods are called调用字符串方法时的脚本引擎异常
【发布时间】:2018-07-04 12:57:54
【问题描述】:

当我使用以下 sn-p 时,我得到一个 ScrptEngineException,表明该对象不支持该属性或方法。

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

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

谁能帮帮我?

【问题讨论】:

    标签: c# clearscript


    【解决方案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 函数,很可能会破坏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多