在LINQ扩展方法中指定泛型类型的原因 [英] Reasons to specify generic types in LINQ extension methods

查看:104
本文介绍了在LINQ扩展方法中指定泛型类型的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅仅出于好奇:

许多LINQ扩展方法既有泛型也有非泛型变体,例如 Any 任何<> 其中其中<> 等。编写我的查询我通常使用非泛型变体,它工作正常。



当用户需要使用泛型方法时,会出现什么情况?

---编辑---



PS:我意识到内部只有通用方法被调用,并且编译器在编译期间试图解析通用括号<> 的内容。
我的问题是什么情况,然后必须明确提供类型,而不是依赖编译器的直觉?

解决

  ObjectSet< User>方案

users = context.Users;
var usersThatMatch = criteria.Aggregate(users,(u,c)=> u.Where(c));

上面的代码不起作用,因为.Where方法不会返回对象集<使用者> 。你可以绕过这两种方式之一。我可以在用户上调用 .AsQueryable()来确保它强类型为IQueryable,或者我可以将特定的类型参数传递给Aggregate方法:

$ (
PersonSet,(u,c)=>) ; u.Where(c));

另一个更常见的例子是 Cast OfType 方法,它们无法推断出您想要的类型,并且在很多情况下首先在非泛型集合上调用。



一般来说,设计LINQ方法的人不费吹灰之力就可以避免在这些泛型方法中使用显式类型,而且大多数情况下您并不需要至。我会说最好知道这是一个选项,但是要避免这样做,除非你觉得有必要。


Just out of curiosity:

Many LINQ extension methods exist as both generic and non-generic variants, for example Any and Any<>, Where and Where<> etc. Writing my queries I usually use the non-generic variants and it works fine.

What would be the cases when one has to use generic methods?

--- edit ---

P.S.: I am aware of the fact that internally only generic methods are called and the compiler tries to resolve the content of the generic brackets <> during compilation. My question is rather what are the cases then one has to provide the type explicitly and not to rely on the compiler's intuition?

解决方案

One example I ran into today:

ObjectSet<User> users = context.Users;
var usersThatMatch = criteria.Aggregate(users, (u, c) => u.Where(c));

The above code won't work because the .Where method doesn't return an ObjectSet<User>. You could get around this one of two ways. I could call .AsQueryable() on users, to make sure it's strongly typed as an IQueryable, or I could pass specific type arguments into the Aggregate method:

criteria.Aggregate<Func<User, bool>, IEnumerable<User>>(
    PersonSet, (u, c) => u.Where(c));

Another couple of more common examples are the Cast and OfType methods, which have no way to infer what type you want, and in many cases are being called on a non-generic collection in the first place.

In general, the folks that designed the LINQ methods went out of their way to avoid the need to use explicit types in these generic methods, and for the most part you don't need to. I'd say it's best to know it's an option, but avoid doing it unless you find it necessary.

这篇关于在LINQ扩展方法中指定泛型类型的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆