简体   繁体   English

创建带有参数的委托函数

[英]Creating delegate function that takes parameters

I have the following delegate function in a Unit Test, and it works great 我在单元测试中具有以下委托函数,并且效果很好

List<Record> RecordSet = FileData.RecordSet;
Record result = RecordSet.Find(
        delegate(Record r)
        {
            return r.UserID == "12345";
        }
    );

and it works great. 而且效果很好。 I need to perform this search multiple times, so I had tried to add it in a function I could call that took the UserID as a parameter, it's VERY similar, but for some reason, ALWAYS returns null. 我需要多次执行此搜索,因此我尝试将其添加到可以调用的函数中,该函数将UserID作为参数,这非常相似,但是由于某种原因,总是返回null。

public Record findRecord(List<Record> RecordSet, string UserID)
{
    Record result = RecordSet.Find(
        delegate(Record r)
        {
            return r.UserID.Trim() == UserID;
        }
    );

    return null;
}

I have also tried it by hard coding "12345" in as the UserID value, that also returns null. 我还尝试通过将“ 12345”作为用户ID值进行硬编码来尝试它,该值也返回null。 What's even stranger is that when I am in debug mode and I look at the values in the RecordSet, I do see the Record with the exact UserID. 甚至更奇怪的是,当我处于调试模式时,当我查看RecordSet中的值时,我确实看到了具有确切UserID的Record。 Yet for some reason, no results, yet the same code and the same data in the first function above returns a result just fine. 出于某种原因,没有结果,但是上面第一个函数中的相同代码和相同数据返回的结果恰好。

Also, FYI, I have fond the LINQ solution to the problem: 此外,仅供参考,我很喜欢LINQ解决方案:

Record result = RecordSet.Where(x => x.UserID == "12345").Select(x => x).First();

But I am specifically looking for reasons why the delegate solution is failing 但是我正在特别寻找委托解决方案失败的原因

The problem is that your method always returns null , because of this line: 问题是您的方法总是由于以下行而返回null

return null;

Replace it with this and you should have better luck: 用它替换它,您应该有更好的运气:

return result;

However, you can simplify this with a lambda expression which takes a Record and returns a bool . 但是,您可以使用接受Record并返回bool的lambda表达式来简化此过程。 Try this: 尝试这个:

return RecordSet.Find(r => r.UserID.Trim() == UserID);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM