【问题标题】:Get System.Type instance from within script (ClearScript)从脚本中获取 System.Type 实例 (ClearScript)
【发布时间】:2020-04-11 07:31:09
【问题描述】:

尝试从 ClearScript 托管的脚本中调用 Enum.Parse 时遇到异常

错误

Error: The non-generic method 'System.Enum.Parse(System.Type, string)' cannot be used with type arguments
--- Script error details follow ---
   Error: The non-generic method 'System.Enum.Parse(System.Type, string)' cannot be used with type arguments
       at translateParameterValue (Script [temp]:11:27) ->          return clr.System.Enum.Parse(app.MyLibrary.MyEnum, value);

脚本

return clr.System.Enum.Parse(app.MyLibrary.MyEnum, value);

我很确定我正确注册了clr 对象(其中包含mscorlib、System 和System.Core)

ClearScript 似乎正在尝试调用,并且很困惑是将第一个参数 app.MyLibrary.MyEnum 设为通用参数还是将其作为 System.Type 参数传递。

问题

在这种情况下,我该怎么做才能正确调用 System.Enum.Parse 函数?

【问题讨论】:

    标签: javascript c# .net clearscript


    【解决方案1】:

    答案比我想象的要简单。由于 ClearScript 将第一个参数视为泛型参数,因此您只需要一个从类型参数返回 System.Type 实例的函数,它可以很简单:

    class Utility
    {
        public Type GetType<T>() {
            return typeof(T);
        }
    }
    

    然后注册到你的ScriptEngine:

    _engine.AddHostObject("Utility", new Utility());
    

    然后在你的脚本中使用它:

    return clr.System.Enum.Parse(Utility.GetType(nepes.DecaTech.CoreData.ProcessStates), value);
    

    ClearScript 还附带一个实用程序类 ExtendedHostFunctions,它提供了几个有用的实用程序功能,包括类似于上述 typeOf(T) 的一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 2011-07-01
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多