如何将委托传递为<函数中的参数

本文关键字:函数 参数 | 更新日期: 2023-09-27 18:06:12

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);
    }

在上述函数中;如何通过"compareValue"作为参数,同时调用"CompareTwoLists"函数?

如何将委托传递为<函数中的参数

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

var people = new List<Person>();
var orders = new List<Order>();
bool result = CompareTwoLists(people, orders, 
    (person, order) => person.Id == order.PersonId);

或作为与委托匹配的方法的引用:

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

您需要创建一个方法(Normal或Anonymous)来匹配该委托的签名。下面是一个示例:

var list1 = new List<string>();
var list2 = new List<int>();
CompareValue<string, int> compareValues = (x, y) => true;
CompareTwoLists(list1, list2, compareValues);

你也可以用普通方法替换匿名方法:

CompareValue<string, int> compareValues = SomeComparingMethod;
static bool SomeComparingMethod(string str, int number)
{
    // code here
}

的另一种方法

你可以改变你的方法使用Func:

public static bool CompareTwoLists<T1, T2>(IEnumerable<T1> list1, IEnumerable<T2> list2, 
                                           Func<T1, T2, bool> compareValue)
{
    return list1.All(x => list2.Any(y => compareValue(x, y)))
        && list2.All(x => list1.Any(y => compareValue(y, x)));
}

并将调用方方法更改为:

Func<User, Role, bool> compareValues = 
                            (u, r) => r.Active
                                   && u.Something == r.Something 
                                   && u.SomethingElse != r.SomethingElse);