Casting/converting 返回到 Func<Foo,bool> 的 lambda 的表达式(序列化后)
Casting/converting an expression back to a lambda of Func<Foo,bool> (after serialization)
我正在尝试序列化和反序列化 Func[Foo,bool]
。我正在使用 Serial.Linq
进行序列化,并且它的一部分似乎有效,但我无法重新组装我的 lambda 谓词。大部分可能源于我对表达式树的理解不足。
我试过以不同的顺序传递类型参数,Expression.Convert
到 Func[Foo,bool]
但我尝试的似乎都不起作用。
using System;
using Serialize.Linq.Serializers;
using System.Linq.Expressions;
public class Foo
{
public string Bar {get; set;}
}
public class Program
{
public static void Main()
{
// Step 1 Serialize it
Expression<Func<Foo,bool>> bark = foo => foo.Bar.Contains("ruff");
var expressionSerializer = new Serialize.Linq.Serializers.ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer());
var serializedQuery = expressionSerializer.SerializeText(bark);
// Step 2 Deserialize it
var barkExpression = expressionSerializer.DeserializeText(serializedQuery);
var barkExpressionReturnArgument = Expression.Parameter(typeof(bool));
var barkExpressionArgument = Expression.Parameter(typeof(Foo));
// var convertedExpression = Expression.Convert(barkExpression, typeof(Func<Foo,bool>));
// How do I get bark back? I've tried a few variations here and can't quite get it. :(
var barkFunction = Expression.Lambda<Func<Foo, bool>>(barkExpression, barkExpressionArgument).Compile();
Console.WriteLine("Hello World");
}
}
我明白了。我想做的太多了,我不需要参数表达式。
反序列化后就是这样:
var barkFunction = ((Expression<Func<Foo, bool>>)barkExpression).Compile()
我正在尝试序列化和反序列化 Func[Foo,bool]
。我正在使用 Serial.Linq
进行序列化,并且它的一部分似乎有效,但我无法重新组装我的 lambda 谓词。大部分可能源于我对表达式树的理解不足。
我试过以不同的顺序传递类型参数,Expression.Convert
到 Func[Foo,bool]
但我尝试的似乎都不起作用。
using System;
using Serialize.Linq.Serializers;
using System.Linq.Expressions;
public class Foo
{
public string Bar {get; set;}
}
public class Program
{
public static void Main()
{
// Step 1 Serialize it
Expression<Func<Foo,bool>> bark = foo => foo.Bar.Contains("ruff");
var expressionSerializer = new Serialize.Linq.Serializers.ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer());
var serializedQuery = expressionSerializer.SerializeText(bark);
// Step 2 Deserialize it
var barkExpression = expressionSerializer.DeserializeText(serializedQuery);
var barkExpressionReturnArgument = Expression.Parameter(typeof(bool));
var barkExpressionArgument = Expression.Parameter(typeof(Foo));
// var convertedExpression = Expression.Convert(barkExpression, typeof(Func<Foo,bool>));
// How do I get bark back? I've tried a few variations here and can't quite get it. :(
var barkFunction = Expression.Lambda<Func<Foo, bool>>(barkExpression, barkExpressionArgument).Compile();
Console.WriteLine("Hello World");
}
}
我明白了。我想做的太多了,我不需要参数表达式。
反序列化后就是这样:
var barkFunction = ((Expression<Func<Foo, bool>>)barkExpression).Compile()