函数谓词到字符串

问题描述 投票:-1回答:2

我对表达式的学习非常基础,我有以下函数谓词

Func<RecordViewModel, Func<ReportModel, bool>> exp = rec => x => x.Firstname == rec.Firstname &&
                                                                 x.Surname == rec.Surname;

var func = exp(new RecordViewModel() { Firstname= "Peter", Surname  = "Jones" });

以下是我的模型和视图模型,

public class ReportModel
{
    public string Firstname { get; set; }
    public string Surname { get; set; }
}
public class RecordViewModel
{
    public string Firstname { get; set; }
    public string Surname { get; set; }
}

我希望将表达式序列化为((ReportModel.Firstname ==“Peter”)AndAlso(ReportModel.Surname ==“Jones”))。

非常感谢任何帮助,

c# linq lambda delegates
2个回答
0
投票

如果你想返回一个字符串,这应该是你的表达式:

Func<RecordViewModel, string> exp = rec (x) => return x.Firstname == rec.Firstname &&
         x.Surname == rec.Surname ? "ReportModel.Firstname" + x.Firstname + " " 
         + "ReportModel.Surname" + " "  rec.Surname : string.empty;

然后你可以通过模型调用表达式:

var func = exp(new RecordViewModel() { Firstname= "Peter", Surname  = "Jones" });

0
投票

所以,如果我理解正确你给了你一个Func(在你的例子中称为exp),你需要为它提供一个toString方法。

你可以使用这样的东西:

Func<Func<ReportModel, bool>, string> toString = func => 
{
    var vm = ((dynamic)func.Target).rec;
    var paramType = func.Method.GetParameters()[0].ParameterType;
    var firstNameProperty = paramType.GetProperties().First(p => p.Name == nameof(vm.Firstname)).Name;
    var surnameProperty = paramType.GetProperties().First(p => p.Name == nameof(vm.Surname)).Name;
    return $"(({paramType.Name}.{firstNameProperty} == \"{vm.Firstname}\") AndAlso ({paramType.Name}.{surnameProperty} == \"{vm.Surname}\"))";
};

Console.WriteLine(toString(exp(viewModel))); 
//returns ((ReportModel.Firstname == "Peter") AndAlso (ReportModel.Surname == "Jones"))

在那里你使用一些反射来获取你的func的参数(并且你知道它们总是有1个)来进行比较。然后根据名称查找该参数的属性。

还有一辆带有qazxsw poi的卡车可以获得qazxsw poi值(你的Record ViewModel)。它可能很脏,但如果有效......

而且,显然,您还要对结果字符串的表示进行硬编码。

© www.soinside.com 2019 - 2024. All rights reserved.