简体   繁体   English

动态linq和运算符重载

[英]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 System.Linq.Dynamic.ParseException未由用户代码处理Message = Operator'+'与操作数类型'Vector2'和'Vector2'不兼容Source = DynamicLINQ Position = 6

How do I get the parser to 'see' the + operator overload on the Vector2 type? 如何让解析器“看到” Vector2类型上的+运算符重载?

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. 麻烦的是,我的类型( Vector2 )不在该列表中,因此它永远不会找到运算符方法。

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 . 使用DynamicLinq库,您需要将签名添加到System.Linq.Dynamic.ExpressionParser找到的其中一个签名接口。 It will only parse operations it recognizes. 它只会解析它识别的操作。

It seems it will look at all the private interfaces found in ExpressionParser . 它似乎将查看ExpressionParser所有私有接口。 Just add an interface within the ExpressionParser and it seems to suppress the error. 只需在ExpressionParser添加一个接口,它似乎可以抑制错误。

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. 为了安全(并且可能符合预期的模式),从IAddSignatures接口添加/扩展可能更安全。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM