C#使用显式定义的Predicate时出现错误。

28 浏览
0 Comments

C#使用显式定义的Predicate时出现错误。

我有一些将在where子句中使用相同谓词的lambda表达式。因此,我第一次使用谓词类型。这是我拥有的内容:\n

Predicate datePredicate = o => o.Date > DateTime.Now.AddDays(-1);

\n当我在查询中使用它时(如下所示),我得到以下错误:\n错误:\n

无法从使用中推断出方法'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)'的类型参数。尝试明确指定类型参数。

\n用法:\n

Type t = collection.Where(datePredicate).SingleOrDefault();

\n有人知道我做错了什么吗?

0
0 Comments

问题的出现原因是编译器无法静态地确定参数oType。我推测o的类型是DateTime。编译器不会做推测的操作 🙂

解决方法是修改代码如下:

Predicate<DateTime> datePredicate = o => o.Date > DateTime.Now.AddDays(-1);

我已经修复了我的回答 - 我认为你在我回答之前编辑了你的问题。

0
0 Comments

问题原因:在使用显式定义的Predicate时,出现了C#错误。在C#中,Predicate是一个委托类型,用于定义一个方法的签名,该方法接受一个参数并返回一个bool值。然而,在给定的代码中,使用了Func而不是Predicate。

解决方法:将Func委托类型替换为Predicate委托类型。因为在使用.Where方法时,它期望一个Func类型的参数。Func委托类型和Predicate委托类型在定义上有所不同,因此需要进行替换。

以下是修改后的代码:

Predicate datePredicate = (o => o.Date > DateTime.Now.AddDays(-1));
collection.Where(datePredicate);

在这里,我们将Func委托类型替换为了Predicate委托类型,以解决C#错误。

感谢Josh的答案起到了作用。你能告诉我为什么需要使用Func而不是Predicate吗?

这个问题的答案可以在stackoverflow.com/questions/4317479中找到。在C#中,.Where方法期望一个Func类型的参数。

以上就是关于C#在使用显式定义的Predicate时出现错误的原因以及解决方法的整理。通过将Func委托类型替换为Predicate委托类型,可以解决这个问题。

0