У меня есть следующий код, который я компилирую в проекте .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;
}
}
}
}
}
но получаю следующие ошибки. У меня 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?)
Вы должны поместить аргумент типа в саму функцию.
public static IEnumerable<T> Filter1<T>(...)
public static class Utility
{
public static IEnumerable<T> Filter1<T>( // Type argument on the function
this IEnumerable<T> input, Func<T, bool> predicate)
{
Если вы не волнует, если его метод расширения или нет, вы можете добавить общий только класс. Я думаю, что вы хотите, чтобы метод расширения.
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)
{
Вам нужно объявить T
, которое встречается после имени метода или имени класса. Измените объявление метода на:
public static IEnumerable<T>
Filter1<T>(this IEnumerable<T> input, Func<T, bool> predicate)
IEnumerable<yourObject>
Здесь вы найдете больше информации: http://msdn.microsoft.com/en-us/library/9eekhta0.aspx
У меня была такая же ошибка, но решения требует немного по-другому. Мне нужно, чтобы изменить это:
public static void AllItemsSatisy(this CollectionAssert collectionAssert, ICollection<T> collection, Predicate<T> predicate)
{ ... }
К этому:
public static void AllItemsSatisy<T>(this CollectionAssert collectionAssert, ICollection<T> collection, Predicate<T> predicate)
{ ... }