|
|
IronRuby > Documentation > .NET Integration > Delegates
DelegatesFrom $1Table of contentsCreating and using generic delegatesYou can create a generic Action delegate by creating a new Action and passing a Ruby block, lambda, or Proc into its constructor: >>> require 'System'
=> true
>>> require 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
=> true
>>> my_action = System::Action.new { puts "Howdy!" }
=> System.Action
>>> my_action.invoke
"Howdy!"
=> nil You can also create generic Action delegates that take an argument (or arguments): >>> my_action = System::Action.of(System::String).new { |name| puts "Howdy, #{name}!" } => System.Action`1[System.String] >>> my_action.invoke "Ryan" Howdy, Ryan! => nil Or you can use the Ruby type, as well: >>> my_action = System::Action.of(String).new { |name| puts "Howdy, #{name}!" }
=> System.Action`1[IronRuby.Builtins.MutableString]
>>> my_action.invoke "Ryan"
Howdy, Ryan!
=> nil Func delegates work much the same way: >>> my_func = System::Func.of(String, String).new { |name| "Howdy, #{name}!" }
=> System.Func`2[IronRuby.Builtins.MutableString,IronRuby.Builtins.MutableString]
>>> result = my_func.invoke "Ryan"
=> "Howdy, Ryan!" So you can see how you could use these to create a delegate to pass into a LINQ expression, here using a lambda and converting the lambda into a System::Func in the System::Linq::Enumerable#select[T,U] call: >>> my_func = lambda { |name| "Howdy, #{name}!" }
=> #<Proc:0x0000056@(unknown):1>
>>> result = my_func.call "Ryan"
=> "Howdy, Ryan"
>>> names = System::Collections::Generic::List.of(String).new
=> []
>>> names.add "Ryan"
=> nil
>>> names.add "Jimmy"
=> nil
>>> names.add "Ivan"
=> nil
>>> query = System::Linq::Enumerable.method(:select).of(String, String).call(names, System::Func.of(String, String).new(my_func))
=> System.Linq.Enumerable+WhereSelectListIterator`2[IronRuby.Builtins.MutableString,IronRuby.Builtins.MutableString]
>>> greetings = System::Linq::Enumerable.method(:to_list).of(String).call(query)
=> ["Howdy, Ryan!", "Howdy, Jimmy!", "Howdy, Ivan!"] Yes, that looks terrible, but we can wrap that up inside a module for a more Ruby-like experience. Moving the creation of the func into the System::Linq::Enumerable#select[T,U] should give you an idea as to where I'm headed, though we'll stick with blocks for now. TODO...
Tags:
|