c# - 动态改变lambda表达式的主体?

标签 c# .net lambda expression func

示例我有以下代码

public class Person
{
    public bool FirstNameIsActive { get; set; }
    public bool SecondNameIsActive { get; set; }
}    

如果我想按属性过滤FirstNameIsActive

Func<Person, bool> predicate1 = x => x.FirstNameIsActive == true;

如果我想按属性过滤SecondNameIsActive

Func<Person, bool> predicate2 = x => x.SecondNameIsActive == true;

我想在运行时将我的谓词更改为

Func<Person, bool> predicate = x => x.PropertyThatIWant == true;

最佳答案

您可以利用修改后的闭包。

//property selector
Func<Person, Boolean> propertySelector = person => person.FirstNameIsActive;

//your predicate
Func<Person, Boolean> predicate = person => propertySelector(person) == true;

//new person with true, false properties.
Person p = new Person() {FirstNameIsActive = true,SecondNameIsActive = false};

Console.WriteLine(predicate(p).ToString()); //prints true

//change the property selector
propertySelector = person => person.SecondNameIsActive;

//now the predicate uses the new property selector
Console.WriteLine(predicate(p).ToString()); //prints false

关于c# - 动态改变lambda表达式的主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20267008/

相关文章:

c# - 通过c#获取多个格式错误的cookie

c# - 更改程序集名称破坏了我的 XAML 设计器

c# - Linq to SQL 计数分组元素生成超时

c# - 如何在控制台项目中使用 Main() 启动窗口。?

c# - 为什么在非 MonoBehaviour 类中调用多个构造函数?

c# - XNA 4.0 打印到 Visual Studio 2012 控制台

python - 将 lambda 表达式应用于数组元素时出现 ValueError

angular - 不支持函数调用。考虑用导出函数的引用替换函数或 lambda

python - 如何忽略元组的解压缩部分作为 lambda 的参数?

c# - 是否可以覆盖 CaSTLe Windsor 3 中的命名注册?