c# - 在 C# 中使用 <TSource> 的泛型方法声明

标签 c# .net

<分区>

我是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 不支持它。

关于c# - 在 C# 中使用 <TSource> 的泛型方法声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507136/

相关文章:

c# - 在 WPF 中,在项目中使用 Struct 或 Class 作为具有 MVVM 模式的模型?

c# - 您将 Form1 重命名为什么?

c# - JSON.NET:反序列化和合并 JSON 字符串

.net - 如何在 InstallScript 中从 .NET DLL 调用方法

c# - 使用退格符附加字符串时从文本文件中删除字符

c# - C#中的 "< >"语法是什么

c# - 如何在 C# 中将 Null 值赋给 Non-Nullable 类型变量?

c# - 如何使用反射转换为通用接口(interface)?

c# - 使用页面方法、Web 服务和自定义 http 处理程序执行 ajax 之间的区别

c# - 为什么递增运算符可以在属性上使用,而 ref 不行