如何使用ErrorListener for IronRuby

我有一个C#程序来执行IronRuby脚本。 但在此之前,我想首先编译该文件,看看是否有任何错误。 但似乎ErrorListener不能正常工作。 我的代码有什么问题吗?

class Program { static void Main(string[] args) { try { ScriptEngine engine = null; engine = Ruby.CreateEngine(); ScriptSource sc = engine.CreateScriptSourceFromFile("MainForm.rb"); ErrorListener errLis = new MyErrorListener(); sc.Compile(errLis); } } class MyErrorListener : ErrorListener { public override void ErrorReported(ScriptSource source, string message, Microsoft.Scripting.SourceSpan span, int errorCode, Microsoft.Scripting.Severity severity) { Console.WriteLine(message); } } 

Ruby文件:

 require "mscorlib" require "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" require "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" include System::Windows::Forms dfasdf error here class MainForm < Form def initialize() self.InitializeComponent() end def InitializeComponent() # # MainForm # self.Name = "MainForm" self.Text = "HelloRubyWin" end end 

你想要做什么似乎实际上没有用。 但不确定是否是一个bug。

要解决它,只需在try / catch块中执行代码并查找MissingMethodExecption。 请注意,如果语法错误在方法内部,这也无济于事,因为IronRuby(或任何其他动态语言)不会对“嵌套”代码执行任何操作,直到它实际执行它为止。

所以一般来说,我认为你不会从你想要做的事情中获得很多价值。

try / catch代码示例:

 ScriptEngine engine = null; engine = Ruby.CreateEngine(x => { x.ExceptionDetail = true; }); ScriptSource sc = engine.CreateScriptSourceFromFile("MainForm.rb"); ErrorListener errLis = new MyErrorListener(); sc.Compile(errLis); try { dynamic d = sc.Execute(); } catch (MissingMethodException e) { Console.WriteLine("Syntax error!"); } 

我研究过这个问题终于找到了首先在下面的Manger中编写ErrorListener类的解决方案。

 public class IronRubyErrors : ErrorListener { public string Message { get; set; } public int ErrorCode { get; set; } public Severity sev { get; set; } public SourceSpan Span { get; set; } public override void ErrorReported(ScriptSource source, string message, Microsoft.Scripting.SourceSpan span, int errorCode, Microsoft.Scripting.Severity severity) { Message = message; ErrorCode = errorCode; sev = severity; Span = span; } } 

然后

 var rubyEngine = Ruby.CreateEngine(); ScriptSource src = rubyEngine.CreateScriptSourceFromFile("test.rb"); IronRubyErrors error = new IronRubyErrors(); src.Compile(error); if (error.ErrorCode != 0) { MessageBox.Show(string.Format("Discription {0} \r\nError at Line No.{1} and Column No{2}", error.Message, error.span.Start.Line, error.span.Start.Column)); } try { if (error.ErrorCode == 0) { var res = src.Execute(); } } catch (MissingMethodException ex) { MessageBox.Show(ex.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } 

因为Ironruby是DLR所以它编译On RunTime如果不是IronRuby关键字的字符(〜,`,^等等)或者你创建了任何语法错误,那么Error将捕获ScriptSource的编译方法和对象ErrorListener类将被填充,如果您使用了未在Ruby库中定义的方法,我们将找到ErrorCode等,例如您已为此类型数字转换键入了方法

  @abc.to_ 

这是不正确的然后它将被捕获在MissingMethodException块中

正确的方法是

  @abc.to_f 

如果你有错误其他然后这些(如除零除外)然后将在exception块中捕获