使用变量序列化表达式
我编写了一些类来将 System.Linq.Expressions 序列化为 DataContracts,以便能够通过 WCF 发送。它工作得很好很好。问题是当我想序列化其中包含变量的表达式时。这是一个解释问题的例子:
public class Foo
{
public string Name { get; set; }
}
// CASE 1
Expression<Func<Foo, bool>> lambda = foo => foo.Name == "Test";
Console.WriteLine(lambda);
// OUTPUT: foo => (foo.Name == "Test")
// CASE 2
var variable = "Test";
lambda = foo => foo.Name == variable;
this.AssertExpression(lambda, "Class Lambda expression with variable.");
// OUTPUT: foo => (foo.Name == value(MyTest+<>c__DisplayClass0).variable)
我在序列化 CASE 2 表达式时没有遇到麻烦,但是我序列化的数据是无用的,因为在服务端,没有什么可以解析 value(MyTest+<; >c__DisplayClass0).variable
所以我需要在序列化该表达式之前解析变量,以便 CASE 2 表达式序列化为与 CASE1 相同的结果
I wrote some classes to serialize System.Linq.Expressions
to DataContracts to be able to send via WCF. It works quite good nice. the problem is when i want to serialize an expression that has a variable in it. here is an example to explain the problem:
public class Foo
{
public string Name { get; set; }
}
// CASE 1
Expression<Func<Foo, bool>> lambda = foo => foo.Name == "Test";
Console.WriteLine(lambda);
// OUTPUT: foo => (foo.Name == "Test")
// CASE 2
var variable = "Test";
lambda = foo => foo.Name == variable;
this.AssertExpression(lambda, "Class Lambda expression with variable.");
// OUTPUT: foo => (foo.Name == value(MyTest+<>c__DisplayClass0).variable)
i am not having trouble to serialize the CASE 2 expression, but the the data i serialize is useless, since on the service side, there is nothing to resolve value(MyTest+<>c__DisplayClass0).variable
so i need to resolve the variables before i serialize that expression so that the CASE 2 expression serializes to same result as CASE1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对 VB 表示抱歉,但是以下摘录是我在评论中提到的代码片段。我不认为它涵盖了所有基础(即它可能没有深入到足够深的地方,所以一定要测试它),但对于simple大多数例子来说它是有效的:代码基于 此 MSDN Expression Visitor示例:
希望这有帮助!
编辑: 我最初遇到的问题是我没有继续走当 MemberAccess 是非
TSource
类时,上述逻辑实际上应该递归地根除这些情况,因此请忽略我原来的评论。我已经在Nullable
子句中留下了(在else if
) 语句中,因为我没有这样做'不要认为现有的逻辑会涵盖这些情况,它也可能与泛型类发生冲突。也就是说,这应该会给你带来好处。如果您不使用表达式访问者,您可以提供更多详细信息/代码吗?
祝你好运!
Sorry for the VB, butthe following extract is the bit of code I meant in my comment. I don't think it covers all the bases(i.e. it may not be drilling down far enough so make sure you test it)but forsimplemost examples it works:The code is based on this MSDN Expression Visitor example:
Hope this helps!
EDIT: The original issue I had was that I didn't continue walking the tree when the MemberAccess was a non
TSource
class, the above logic should actually recursively root those cases out so ignore my original comment. I've left in theNullable<T>
clause (on theelse if
) statement as I don't think the existing logic will cover those cases, it may also struggle with Generic classes.That said, this should put you in good stead. If you're not using the Expression Visitor, can you provide some more details/code?
Good luck!