And I’m trying to call it from IronRuby project with Ruby object as an
argument.
comp = Computer.new
session.method(:Store).of(Computer).call(comp) #session is another user created .Net object, which has the method Store
And when I’m running the project an error pops up
“GenericArguments[0], “IronRuby.Builtins.RubyObject”, in “Void
StoreT” does not satisfy the restriction of the type parameter “T””
I guess that .Net generic just can’t accept RubyObject as an argument.
But can I somehow bypass that restriction?
Re: [Ironruby-core] Calling .Net generic method with Ruby object
Orion E.
Wed, 18 Jul 2012 13:59:01 -0700
The .NET method can’t accept normal IronRuby objects, because of the
new()
constraint.
IronRuby objects behind the scenes are all instances of A .NET class
called RubyObject - you can see it’s code here:
RubyObject has 2 constructors, both of which require parameters… Your
new() constraint says “I can only accept methods with public
zero-argument
constructors”… RubyObject doesn’t satisfy this (and neither do many
many
other .NET classes), so it simply doesn’t work.
If you remove the new() constraint, you can pass Ruby objects to the
Store
method.
There is another way to do this also. If you create a blank .NET class
with a default constructor, and have your ruby classes derive from it,
then IronRuby will create instances of those classes instead of
RubyObject.
You can then call the Store method and use the .NET class as the T.
Remember, C# can’t see any of the ruby methods, but it will also allow
you
to “store” the object.
Here’s my example code:
C#:
public static class Demo
{
public static void Store(T obj) where T : class, new()
{
Console.WriteLine(“Storing {0}”, obj);
}
}
public class SimpleObject
{
public SimpleObject() { }
}
This prints “Storing IronRuby.Classes.SimpleObject$1”
If it’s ok, can I ask what you’re trying to do here? Normal .NET code
can’t really interact with ruby objects unless it’s built to use the C#
4
dynamic keyword, or has special knowledge of the Dynamic Language
Runtime
API’s… If you’re just putting ruby objects in a list so that ruby code
can retrieve them later that will be fine, but if you’re trying to do
other things, you may run into problems…