-1

I get a exception if I try to use GetCompletionValue with Invoker.
How can i execute the run function with IIFE lexical scope?

Javascript:

(function(){
  function run() {
    logger('teste logger');

    var file = new System.IO.StreamWriter('log.txt');
        file.WriteLine('Write file test');
        file.Dispose();
  }

  return {
    'run': run
  }
})();

My Invoker:

public void Execute(string code, string functionName)
{
  _engine.Execute(code).GetCompletionValue();
  _engine.Invoke(functionName); // -- run function
}

Error:

Exception has occurred: CLR/System.ArgumentException
An exception of type 'System.ArgumentException' occurred in Jint.dll but was not handled in user code: 'Can only invoke functions'
   at Jint.Engine.Invoke(JsValue value, Object thisObj, Object[] arguments)
   at Jint.Engine.Invoke(String propertyName, Object thisObj, Object[] arguments)
   at Jint.Engine.Invoke(String propertyName, Object[] arguments)
4

1 回答 1

1

如何使用 IIFE 词法范围执行 run 函数?

导致“System.ArgumentException”的原因是Javascript. 格式功能码无效。像下面的代码一样改变它:

          function run() {
            logger('teste logger');

            var file = new System.IO.StreamWriter('log.txt');
                file.WriteLine('Write file test');
                file.Dispose();
          }

至于词法范围,您还可以尝试以下代码:

        String code = @"

          function go(){
                function run() {
                logger('teste logger');

                var file = new System.IO.StreamWriter('log.txt');
                    file.WriteLine('Write file test');
                    file.Dispose();
                }

                return run();
            }

        ";
        Execute(code, "go");



.NET Core 3.1 中使用 Jint 的 ConsoleApplication 示例

class Program
{

    public static Engine _engine = new Engine(cfg => cfg.AllowClr());


    static void Main(string[] args)
    {
        _engine.SetValue("logger", new Action<object>(Console.WriteLine));

        String code = @"

          function run() {
            logger('teste logger');

            var file = new System.IO.StreamWriter('log.txt');
                file.WriteLine('Write file test');
                file.Dispose();
          }

        ";
        Execute(code, "run");
    }

    public static void Execute(string code, string functionName)
    {
        _engine.Execute(code).GetCompletionValue();
        _engine.Invoke(functionName); // -- run function
    }
}

测试

它按run预期工作。

在此处输入图像描述

于 2020-08-20T09:21:59.257 回答