Dynamic linq and operator overloads
Asked Answered
S

1

10

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.

Sibelius answered 12/1, 2012 at 15:34 Comment(2)
George, I've reverted my position on whether or not you should just create any interface or extend from one of the given interfaces. I think it would be safer to extend from one of the interfaces instead. There may or may not be additional type checking (such as does the type actually support addition) in the future or whatnot.Aerialist
Good point, thanks; i've altered my code accordingly.Sibelius
A
2

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);
}
Aerialist answered 12/1, 2012 at 19:1 Comment(1)
Possibly even the ISubtractSignatures interface since subtraction is a valid operation on Vector2.Aerialist

© 2022 - 2024 — McMap. All rights reserved.