猿问

函数谓词到字符串

我的表达学习真的很基础,我有以下函数谓词


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"))。


非常感谢任何帮助,


红颜莎娜
浏览 145回答 2
2回答

阿波罗的战车

所以,如果我对你的理解正确,你会得到一个Func(在你的例子中称为 exp),你需要为它提供一个 toString 方法。你可以使用这样的东西:Func<Func<ReportModel, bool>, string> toString = func =>&nbsp;{&nbsp; &nbsp; var vm = ((dynamic)func.Target).rec;&nbsp; &nbsp; var paramType = func.Method.GetParameters()[0].ParameterType;&nbsp; &nbsp; var firstNameProperty = paramType.GetProperties().First(p => p.Name == nameof(vm.Firstname)).Name;&nbsp; &nbsp; var surnameProperty = paramType.GetProperties().First(p => p.Name == nameof(vm.Surname)).Name;&nbsp; &nbsp; return $"(({paramType.Name}.{firstNameProperty} == \"{vm.Firstname}\") AndAlso ({paramType.Name}.{surnameProperty} == \"{vm.Surname}\"))";};Console.WriteLine(toString(exp(viewModel)));&nbsp;//returns ((ReportModel.Firstname == "Peter") AndAlso (ReportModel.Surname == "Jones"))在那里,您使用一些反射来获取 func 的参数(并且您知道它们总是有 1 个)来进行比较。然后根据名称查找该参数的属性。还有一个小技巧dynamic可以获取rec值(您的 RecordViewModel)。它可能很脏,但如果它有效......而且,显然,您还对结果字符串的表示进行了硬编码。

犯罪嫌疑人X

如果你想返回一个字符串,这应该是你的表达式:Func<RecordViewModel, string> exp = rec (x) => return x.Firstname == rec.Firstname &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x.Surname == rec.Surname ? "ReportModel.Firstname" + x.Firstname + " "&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;+ "ReportModel.Surname" + " "&nbsp; rec.Surname : string.empty;然后你可以通过传入模型来调用表达式:var func = exp(new RecordViewModel() { Firstname= "Peter", Surname&nbsp; = "Jones" });
随时随地看视频慕课网APP
我要回答