我是C#的初学者,只是一个关于泛型方法的问题。例如:
public static IQueryable<TResult> Where<TSource>(...)
所以我们只调用这个 LINQ 方法:
var test = _context.Recipes.Where(r => !r.IsDeleted)
代替
var test = _context.Recipes.Where<Recipe>(r => !r.IsDeleted)
那么为什么我们不直接将泛型方法声明为
public static IQueryable<TResult> Where(...)
签名是
public static IQueryable<TSource> Where<TSource> (this IQueryable<TSource> source,...)
之所以可以调用 SomeQueryable.Where(r => ...)
是因为类型推断
Generic Methods (C# Programming Guide)
The compiler can infer the type parameters based on the method
arguments you pass in; it cannot infer the type parameters only from a
constraint or return value. Therefore type inference does not work
with methods that have no parameters. Type inference occurs at compile
time before the compiler tries to resolve overloaded method
signatures. The compiler applies type inference logic to all generic
methods that share the same name. In the overload resolution step, the
compiler includes only those generic methods on which type inference
succeeded.
注意:类型推断有一些注意事项,编译器只能以全有或全无的方式推断类型,这意味着它必须推断所有类型,否则我将推断无,相反称为部分推断,.Net 不支持它。