繁体   English   中英

从脚本中获取 System.Type 实例 (ClearScript)

[英]Get System.Type instance from within script (ClearScript)

尝试从通过 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 object (这包含mscorlibSystemSystem.Core

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

问题

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

答案比我想象的要简单。 由于 ClearScript 将第一个参数视为通用参数,因此您只需要一个 function 从类型参数返回一个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 还附带了一个实用程序 class ExtendedHostFunctions ,它提供了几个有用的实用程序函数,包括一个类似于上述typeOf(T)的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM