javascriptc#.netclearscript

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

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)

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.

Question

What can I do to correctly invoke System.Enum.Parse function given this scenario?


Solution

  • 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:

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

    Then register it to your 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).