简体   繁体   English

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

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

I'm getting an exception when trying to call Enum.Parse from within a script hosted via ClearScript尝试从通过 ClearScript 托管的脚本中调用 Enum.Parse 时出现异常

Error错误

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);

Script脚本

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

I'm pretty sure I registered the clr object correctly (this contains mscorlib , System and System.Core )我很确定我正确注册了clr object (这包含mscorlibSystemSystem.Core

It seems ClearScript is trying to invoke and is getting confused whether to make the first parameter app.MyLibrary.MyEnum a generic parameter or pass it as a System.Type parameter.似乎 ClearScript 正在尝试调用,并且对是否将第一个参数app.MyLibrary.MyEnum通用参数或将其作为System.Type参数传递感到困惑。

Question问题

What can I do to correctly invoke System.Enum.Parse function given this scenario?在这种情况下,我该怎么做才能正确调用System.Enum.Parse function?

The answer was simpler than I thought.答案比我想象的要简单。 Since ClearScript was treating the first argument like a generic parameter, you just need a function that returns a System.Type instance from the type parameter which can be as simple as:由于 ClearScript 将第一个参数视为通用参数,因此您只需要一个 function 从类型参数返回一个System.Type实例,它可以很简单:

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

Then register it to your ScriptEngine :然后将其注册到您的ScriptEngine

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

Then use it in your script as:然后在你的脚本中使用它:

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

ClearScript also ships with a utility class ExtendedHostFunctions which provides several useful utility functions, including one similar to the above typeOf(T) . ClearScript 还附带了一个实用程序 class ExtendedHostFunctions ,它提供了几个有用的实用程序函数,包括一个类似于上述typeOf(T)的函数。

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

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