C# 中的谓词问题
我有以下方法定义(已编辑以删除多余的泛型):
public static T SearchAgaistValues<T>(Dictionary<string, string> input,
string key, List<T> values, Predicate<T> match, out string[] cmdParams)
我的简化要求如下。我需要在 input
中搜索 key
,如果找到,请查看其值是否出现在 values
中。但是,values
是通用的(并且显然会包含我需要匹配的字符串)。因此,在我看来,我必须传递一个谓词方法来执行匹配。
然而,我见过的每个 Predicate键
值与值
中的每个项目进行比较。但是,我无法传递这些值。
我不知道如何使用基于委托的匹配方法在 foreach 循环之外执行此操作。
我在这里错过了什么吗?
I have the following method definition (EDITED to remove redundant generic):
public static T SearchAgaistValues<T>(Dictionary<string, string> input,
string key, List<T> values, Predicate<T> match, out string[] cmdParams)
My simplified requirements are as follows. I need to search input
for key
, and if found, see if its value appears in values
. However, values
is generic (and will obviously contain a string that I need to match). Therefore, the way I see it, I have to pass a predicate method to perform the matching.
However, every example of Predicate<T>
I have seen has a hard coded comparitor. I need to compare the found key's
value to each item in values
. I cannot pass these values, however.
I can't see how to do this outside of a foreach loop with a delegate based match method.
Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,你有两种选择,而无需改变疯狂的要求。
选项 1 是使用
Func
而不是Predicate
。这样谓词就可以根据需要在 string 和 T1 之间进行转换并返回布尔匹配结果。或者,您可以传递额外的
Converter
参数,将查找的字符串转换为 T1,然后使用谓词进行比较。但这两种情况都不太理想。这个函数听起来更像是一个寻找解决方案的问题,而不是相反。签名有点疯狂,似乎可以通过重述需求或将其分解成碎片来大大简化。
As I see it you have two options, without changing crazy requirements.
Option 1 is to use
Func<string, T1, bool>
instead ofPredicate<T1>
. This way the predicate can convert between string and T1 as needed and return the boolean matched result.Alternatively you can pass an additional
Converter<T1, string>
parameter to convert the looked-up string to a T1 and then compare using the predicate.Both cases are less than ideal though. This function sounds a lot more like a problem looking for a solution than the other way around. The signature is a bit crazy and seems like it can be greatly simplified by restating the requirements or breaking it up into pieces.