序列化表达式树 [英] Serialize expression tree
问题描述
我正在用c#开发分布式系统,遇到了障碍.
I'm doing a distributed system in c# and have encountered a barrier.
我需要能够序列化类型的谓词
I need to be able to serialize Predicate with type
Predicate<ICollection<IEntity>> p = (entities => entities.OfType<Person>().Count() <= 3);
我相信在.net中这是不可能的,所以我的问题是是否存在任何可以解决问题的框架.
I belive this is not possible in .net so my question is if there exists any frameworks that can do the trick.
我已经尝试了两个框架,但是一直遇到这样的问题:它们无法序列化需要集合或列表的谓词
I've already tried a couple of frameworks, but keep running into the problem that their are not able to serialize predicates that takes a collection or list
希望任何人都知道解决方案.已经被这个问题困扰了几个星期了...
Hope anyone knows a solution. Have been stuck with this problem for a couple of weeks now...
推荐答案
我的解决方案:
让问题搁置了很长时间后,终于可以使用json.net和Aq.ExpressionJsonSerializer( https://github.com/aquilae/expression-json-serializer )
After putting the issue to rest for a long time a finally managed to solve my problem using json.net and Aq.ExpressionJsonSerializer (https://github.com/aquilae/expression-json-serializer)
public class JsonNetAdapter : IOconSerializer
{
private readonly JsonSerializerSettings _settings;
public JsonNetAdapter(JsonSerializerSettings settings = null)
{
var defaultSettings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects};
defaultSettings.Converters.Add(new ExpressionJsonConverter(Assembly.GetAssembly(typeof(IOconSituation))));
_settings = settings ?? defaultSettings;
}
public string Serialize<T>(T obj)
{
return JsonConvert.SerializeObject(obj, _settings);
}
public T Deserialize<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json, _settings);
}
}
像魅力一样工作!
这篇关于序列化表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!