gpt4 book ai didi

c# - 添加代表 : unexpected results when adding two Func

转载 作者:太空狗 更新时间:2023-10-30 00:51:49 26 4
gpt4 key购买 nike

所以这是我在使用表达式和函数时观察到的非常奇怪的行为。

public int Age { get; set; }
public EyeColor EyeColor { get; set; }
public int Weight { get; set; }

public Func<Person, bool> AgeAndEyesMatch
{
get { return IsPersonYoung().Compile() + PersonHasRightEyeColor().Compile(); }
}

public Func<Person,bool> AgeAndWeightMatch
{
get { return IsPersonYoung().Compile() + IsPersonInShape().Compile(); }
}

private Expression<Func<Person, bool>> PersonHasRightEyeColor()
{
return person => person.EyeColor == EyeColor;
}

private Expression<Func<Person, bool>> IsPersonYoung()
{
return person => person.Age <= Age;
}

private Expression<Func<Person, bool>> IsPersonInShape()
{
return person => person.Weight <= Weight;
}

在控制台应用程序中,我创建了以下“人员”

var mark = new Person
{
Age = 30,
EyeColor = EyeColor.Blue,
Height = 69,
Name = "Mark",
Weight = 185
};
var austin = new Person
{
Age = 70,
EyeColor = EyeColor.Brown,
Height = 64,
Name = "Austin Powers",
Weight = 135
};
var napolean = new Person
{
Age = 17,
EyeColor = EyeColor.Green,
Height = 71,
Name = "Napolean Dynamite",
Weight = 125
};

主程序列出了这些人并将其称为“人”,只是要求用户提供年龄、眼睛颜色和体重的搜索参数。然后按如下方式调用人员列表:newList = people.Where(person => coolKidCriteria.AgeAndEyesMatch(person)).ToList();newNewList = people.Where(person => coolKidCriteria.AgeAndWeightMatch(person)).ToList();

鉴于 MaxAge = 20、EyeColor = EyeColor.Blue、MaxWeight=150 的参数,我希望第一个列表为空,第二个列表仅包含 Napolean Dynamite...但是我收到的是第一个列表与 Mark,第二个列表填充了 Austin Powers 和 Napolean Dynamite...我能想到的意外行为的唯一原因是两个 Func 的“+”运算符导致了问题。只是想知道是否有人可以解释为什么。我推断只有两个函数中的第二个函数被评估:AgeAndEyeColor = (age does not evaluate) + (eye color match for Mark only) and AgeAndInShape = (age does not evaluate) + (Austin and Napolean .InShape = = 真)

对于应用程序的歧视性语气,我深表歉意...真的,这对我来说只是一个学习的东西,我没有其他背景。

最佳答案

当您使用 + 时在两个 Func<int, bool> s,您没有告诉 C# 创建单个 Func<int, bool>调用你的两个原始函数和&&结果在一起。相反,您是在告诉 C# 创建一个 multicast delegate调用两个函数并返回最后一个结果

例如,

static Func<int, bool> Fizz = i => i % 3 == 0;
static Func<int, bool> Buzz = i => i % 5 == 0;
static Func<int, bool> FizzBuzz = Fizz + Buzz;

static void Main(string[] args)
{
var fiveIsFizzBuzz = FizzBuzz(5); // gives true
}

如果你想要一个 && ,您必须手动执行此操作:

static Func<int, bool> FizzBuzz = i => Fizz(i) && Buzz(i);

如果一切都必须是表达式,您可以使用以下内容:

static Expression<Func<int, bool>> Fizz = i => i % 3 == 0;
static Expression<Func<int, bool>> Buzz = i => i % 5 == 0;
static Expression<Func<int, bool>> FizzBuzz = Expression.Lambda<Func<int, bool>>(
Expression.AndAlso(Fizz.Body, Expression.Invoke(Buzz, Fizz.Parameters[0])),
Fizz.Parameters[0]);

关于c# - 添加代表 : unexpected results when adding two Func<T, TResult>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24883136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com