谓词帮助代表
我正在尝试创建一个重载的 Add 方法作为 OrderedDictionary 类的扩展,并希望基于某些柯里化谓词添加键/值。
调用代码如下所示:
OrderedDictionary dict = new OrderedDictionary();
Predicate<int> lessThan5 = i=>; i < 5;
Predicate<string> lenOf2 = s=> s.length == 2;
dict.Add("01","Name", lessThan5 );
dict.Add("02","place", lenOf2);
我创建了一个如下所示的扩展方法:
public static class CollectionExtensions
{
public static void Add(this OrderedDictionary s, string k, string v, Predicate p)
{
if (p)
{
d.Add(k, v);
}
}
}
但它不起作用,因为我收到编译器错误“无法将谓词转换为布尔值”。
有谁知道我缺少什么?
感谢您的任何帮助。 -基思
I am trying to create an overloaded Add method as an extension to the OrderedDictionary class and would like to add the key/value based on some curried predicate.
The calling code would look like this:
OrderedDictionary dict = new OrderedDictionary();
Predicate<int> lessThan5 = i=>; i < 5;
Predicate<string> lenOf2 = s=> s.length == 2;
dict.Add("01","Name", lessThan5 );
dict.Add("02","place", lenOf2);
I have created an extension method like so:
public static class CollectionExtensions
{
public static void Add(this OrderedDictionary s, string k, string v, Predicate p)
{
if (p)
{
d.Add(k, v);
}
}
}
But it doesn't work because I get a compiler error reading "cannot convert Predicate to bool".
Does anyone know what I am missing?
Thanks for any help.
-Keith
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您没有评估谓词来检查谓词是否满足。现在,您的问题尚不清楚您是否希望谓词测试键或值。下面检查密钥。您还应该考虑让该方法返回
bool
来指示成功或失败,就像我在这里所做的那样。用法;
实际上,您可以对此进行概括,因为
OrderedDictionary
不是强类型的。用法:
The issue is that you are not evaluating your predicate to check and see whether or not the predicate is satisfied. Now, it's not clear from your question if you want the predicate to test the key or the value. The following checks the key. You should also consider having the method return
bool
indicating success or failure as I've done here.Usage;
You can actually generalize this a bit since
OrderedDictionary
is not strongly-typed.Usage: