我有以下代码,我正在.NET 4.0项目中编译
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
public static class Utility
{
public static IEnumerable<T> Filter1(this IEnumerable<T> input, Func<T, bool> predicate)
{
foreach (var item in input)
{
if (predicate(item))
{
yield return item;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但得到以下错误.我已将System.dll作为默认值包含在引用中.我可能做错了什么?
Error 1 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
Error 2 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
Error 3 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
Run Code Online (Sandbox Code Playgroud)
Pau*_*ips 55
您必须将type参数放在函数本身上.
public static IEnumerable<T> Filter1<T>(...)
Run Code Online (Sandbox Code Playgroud)
SwD*_*n81 41
public static class Utility
{
public static IEnumerable<T> Filter1<T>( // Type argument on the function
this IEnumerable<T> input, Func<T, bool> predicate)
{
Run Code Online (Sandbox Code Playgroud)
如果你不关心它是否是一个扩展方法,你可以在类中添加一个通用约束.我的猜测是你想要扩展方法.
public static class Utility<T> // Type argument on class
{
public static IEnumerable<T> Filter1( // No longer an extension method
IEnumerable<T> input, Func<T, bool> predicate)
{
Run Code Online (Sandbox Code Playgroud)
spe*_*der 15
您需要声明T
,这发生在方法名称或类名称之后.将您的方法声明更改为:
public static IEnumerable<T>
Filter1<T>(this IEnumerable<T> input, Func<T, bool> predicate)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56457 次 |
最近记录: |