示例我有以下代码
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/