gpt4 book ai didi

c# - 如何在函数中将委托(delegate)作为 参数传递

转载 作者:太空宇宙 更新时间:2023-11-03 12:40:06 26 4
gpt4 key购买 nike

public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);
public static bool CompareTwoLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2> list2, CompareValue<T1, T2> compareValue)
{
return list1.Select(item1 => list2.Any(item2 => compareValue(item1, item2))).All(search => search)
&& list2.Select(item2 => list1.Any(item1 => compareValue(item1, item2))).All(search => search);
}

在上面的函数中;如何在调用“CompareTwoLists”函数时将“compareValue”作为参数传递?

最佳答案

使用与委托(delegate)匹配的 lambda 表达式:

var people = new List<Person>();
var orders = new List<Order>();

bool result = CompareTwoLists(people, orders,
(person, order) => person.Id == order.PersonId);

或者作为对匹配委托(delegate)的方法的引用:

static bool PersonMatchesOrder(Person person, Order order)
{
return person.Id == order.PersonId;
}

bool result = CompareTwoLists(people, orders, PersonMatchesOrder);

关于c# - 如何在函数中将委托(delegate)作为 <T> 参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39383056/

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