【问题标题】:IEnumerable reports compiler error when used with the namespace System.CollectionsIEnumerable 与命名空间 System.Collections 一起使用时报告编译器错误
【发布时间】:2013-10-16 16:42:54
【问题描述】:

我正在查看 Internet 中已经存在的这种 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);
        }
    }
}

【问题讨论】:

  • 您的术语在这里有点偏离。您得到的是编译器错误,而不是异常。异常发生在运行时。
  • @DanielHilgarth:是的,你是对的。已编辑:)
  • IEnumerable 是一种类型,而不是一种方法,因此没有返回类型。IEnumerable&lt;T&gt; 是一个不同的类型,它是具有一个类型参数的泛型类型
  • @RuneFS:酷。说得通。谢谢。

标签: c# .net .net-4.0 extension-methods


【解决方案1】:

using System.Collections; 替换为using System.Collections.Generic;

【讨论】:

  • 这就成功了。谢谢。但是,我也注意到命名空间为System.Collections 时,static IEnumerable Squares 行也有效。为什么 ? (注意,我没有将任何类型指定为 吗?)
  • @nowhewhomustnotbenamed.:因为有两个接口:非泛型System.Collections.IEnumerable和泛型System.Collections.Generic.IEnumerable&lt;T&gt;
  • @DanielHilgarth:感谢您指出这一点。让我看看。
猜你喜欢
  • 2011-07-28
  • 2016-12-04
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
相关资源
最近更新 更多