.netでironrubyスクリプトを動いて、ironrubyでReflectionを使うなど

今日は会社で暇の時間にIronRubyを試した。
自分のプログラムに、String形式のrubyスクリプトを使える。
機動性は高い
そしてスクリプトに.netのライブラリーを使える。
だったらReflection機能を試そうと思った。
スクリプトはこのようである:


include System::Reflection
include System::Collections::Generic
include System

st = Type.GetType('System.String')
a = List[System::Type].new
a.Add(st)
t = Type.GetType('System.Console')
m = t.GetMethod('WriteLine', a.ToArray)
p = List[System::Object].new
p1 = System::String.new('Hello world')
p.Add(p1)
m.Invoke(nil, p.ToArray)

配列の取得方法はわからないから List.ToArray を使った
結果は

IronRuby 1.0.0.0 on .NET 2.0.50727.5420
Copyright (c) Microsoft Corporation. All rights reserved.

>>> include System::Reflection
=> Object
>>> include System::Collections::Generic
=> Object
>>> include System
=> Object

>>> st = Type.GetType('System.String')
=> System.String
>>> a = List[System::Type].new
=>
>>> a.Add(st)
=> nil
>>> t = Type.GetType('System.Console')
=> System.Console
>>> m = t.GetMethod('WriteLine', a.ToArray)
=> Void WriteLine(System.String)
>>> p = List[System::Object].new
=>

>>> p1 = System::String.new('Hello world')
=> 'Hello world'
>>> p.Add(p1)
=> nil
>>> m.Invoke(nil, p.ToArray)
Hello world
=> nil

.netにIronRubyのスクリプトを使い手順:
まず、IronRuby.Ruby.CreateEngine()関数を呼び、Microsoft.Scripting.Hosting.ScriptEngine(略してScriptEngine)オブジェクトを取得する
そして、ScriptEngine.Executeで、String形式のスクリプトは動く
あと、変数は複数のScriptEngine.Executeに使うため、Microsoft.Scripting.Hosting.ScriptScope(略してScriptScope)オブジェクトは必要である。ScriptEngine.CreateScopeで取得可能。ScriptEngine.Executeを呼ぶ出すとき第二引数はScriptScopeです。