C# IEnumerable在与命名空间System.Collections一起使用时报告编译器错误
我在看这个C# IEnumerable在与命名空间System.Collections一起使用时报告编译器错误,c#,.net,.net-4.0,extension-methods,C#,.net,.net 4.0,Extension Methods,我在看这个Squares扩展方法,这个方法已经在互联网上出现了。我找不到这个。编译器报告类似于,“非泛型类型`System.Collections.IEnumerable'不能与类型参数一起使用” 你知道下面的代码有什么问题吗 非常感谢您的帮助 using System.IO; using System; using System.Collections; static class Program { static IEnumerable<int> Squares (t
Squares
扩展方法,这个方法已经在互联网上出现了。我找不到这个。编译器报告类似于,“非泛型类型`System.Collections.IEnumerable'不能与类型参数一起使用”
你知道下面的代码有什么问题吗
非常感谢您的帮助
using System.IO;
using System;
using System.Collections;
static class Program {
static IEnumerable<int> Squares (this int from, int to) {
for (int i=from;i<=to;i++)
{
yield return (int)i*i;
}
}
static void Main(string[] args)
{
var min=1;
foreach (int i in min.Squares(4))
{
Console.WriteLine(i);
}
}
}
使用System.IO;
使用制度;
使用系统集合;
静态类程序{
静态IEnumerable Squares(此int-from,int-to){
对于(int i=from;i替换使用System.Collections;
替换为使用System.Collections.Generic;
替换使用System.Collections;
替换为使用System.Collections.Generic;
就是这样。谢谢。但是,我还注意到,使用System.Collections
名称空间,行是静态的IEnumerable Squares
也可以。为什么?(注意,我没有指定任何类型?)@现在他不必命名。因为有两个接口:非泛型接口和泛型接口。@DanielHilgarth:谢谢你指出这一点。让我看看。就是这样。谢谢。但是,我也注意到,在名称空间为System.Collections
的情况下,静态IEnumerable Squares
行也可以工作。为什么?(注意,我没有指定任何类型。)@nowhewhomustnotbenamed.:因为有两个接口:非泛型和泛型。@DanielHilgarth:谢谢你指出这一点。让我看看。你的术语在这里有点偏离。你得到的是编译器错误而不是异常。异常发生在运行时。@DanielHilgarth:是的,你是对的。编辑:)IEnumerable
是一个类型,而不是一个方法,因此没有返回类型。有一个不同的类型IEnumerable
,它是一个具有一个类型的泛型类型argument@RuneFS:酷。有道理。谢谢。你的术语在这里有点离题。你得到的是编译器错误而不是异常。异常发生在运行时。@DanielHilgarth:是的,你是对的。编辑:)IEnumerable
是一个类型,而不是一个方法,因此没有返回类型。有一个不同的类型IEnumerable
,它是一个具有一个类型的泛型类型argument@RuneFS:酷,有道理,谢谢。