Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic linq and operator overloads

Consider the code below:

var vectorTest = new Vector2(1, 2) + new Vector2(3, 4); // Works

var x = Expression.Parameter(typeof(Vector2), "x");
var test = System.Linq.Dynamic
                 .DynamicExpression.ParseLambda(new[] { x }, null, "x = x + x");

Running it, I get the exception below:

System.Linq.Dynamic.ParseException was unhandled by user code Message=Operator '+' incompatible with operand types 'Vector2' and 'Vector2' Source=DynamicLINQ Position=6

How do I get the parser to 'see' the + operator overload on the Vector2 type?

EDIT: I also get the same issue with the = operator.
Looking at the source I can see why, it looks at a special interface that lists loads of methods, for simple types and if it can't find it, then it raises the exception. Trouble is, my type (Vector2) isn't in that list, so it won't ever find the operator methods.

like image 229
George Duckett Avatar asked Jan 12 '12 15:01

George Duckett


1 Answers

Working with the DynamicLinq library, you'll need to add the signature to one of the signature interfaces found in the System.Linq.Dynamic.ExpressionParser. It will only parse operations it recognizes.

It seems it will look at all the private interfaces found in ExpressionParser. Just add an interface within the ExpressionParser and it seems to suppress the error.

interface ICustomSignatures
{
    void F(Microsoft.Xna.Framework.Vector2 x, Microsoft.Xna.Framework.Vector2 y);
}

Just to be safe (and possibly fit the intended pattern), it might be safer to add to/extend from the IAddSignatures interface.

interface ICustomSignatures : IAddSignatures
{
    void F(Microsoft.Xna.Framework.Vector2 x, Microsoft.Xna.Framework.Vector2 y);
}
like image 111
Jeff Mercado Avatar answered Oct 25 '22 06:10

Jeff Mercado